Q:

C++ Class and Objects | Find output programs | Set 3

belongs to collection: C++ find output programs

0

This section contains the C++ find output programs with their explanations on C++ Class and Objects (set 3).

Program 1:

#include <iostream>
using namespace std;

class Sample {
    int X;

public:
    void set(int x)
    {
        X = x;
    }
    void print()
    {
        cout << X << " ";
    }

} A, B;

int main()
{
    A.set(10);
    B.set(20);

    A.print();
    B.print();

    return 0;
}

Program 2:

#include <iostream>
using namespace std;

const class Sample {
    int X;

public:
    void set(int x)
    {
        X = x;
    }
    void print()
    {
        cout << X << " ";
    }
};

int main()
{
    Sample A;
    Sample B;

    A.set(10);
    B.set(20);

    A.print();
    B.print();

    return 0;
}

Program 3:

#include <iostream>
using namespace std;

class Sample {
    int X;

public:
    void set(int x);
    void print();
};

void Sample : set(int x)
{
    X = x;
}

void Sample : print()
{
    cout << X << " ";
}

int main()
{
    Sample A;
    Sample B;

    A.set(10);
    B.set(20);

    A.print();
    B.print();

    return 0;
}

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Anwser Program 1:

Output:

10 20

Explanation:

In the above program, we created class Sample and two objects A and B using before semicolon at the end of the class.

In the main() function, we call set() and print() function, then it will print "10 20" on the console screen.

Anwser Program 2:

Output:

main.cpp:4:1: error: ‘const’ can only be specified for objects and functions
 const class Sample {
 ^~~~~

Explanation:

The above program will generate an error because we cannot use the const keyword with class declaration. The const keyword can be used with data members and member functions of the class.

Anwser Program 3:

Output:

main.cpp:12:13: error: found ‘:’ in nested-name-specifier, expected ‘::’
 void Sample : set(int x)
             ^
main.cpp:17:13: error: found ‘:’ in nested-name-specifier, expected ‘::’
 void Sample : print()
             ^

Explanation:

The above program will generate errors because in the above program we declare member function inside the class and defined outside the class. But we use the colon operator instead of scope resolution operator ("::" ).

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C++ find output programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C++ Class and Objects | Find output programs | Set... >>
<< C++ Class and Objects | Find output programs | Set...