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

This section contains the C++ find output programs with their explanations on C++ Class and Objects (set 3).
Submitted by Nidhi, on June 10, 2020

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;
}

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.

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;
}

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.

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;
}

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 ("::" ).






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.