×

C++ Tutorial

C++ Data types

C++ Operators & Keywords

C++ Conditional Statements

C++ Functions

C++ 'this' Pointer, References

C++ Class & Objects

C++ Constructors & Destructors

C++ Operator overloading

C++ 11 (Advance C++)

C++ Preparation

C++ Header Files & Functionsr

Data Structure with C++

C++ - Miscellaneous

C++ Programs

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!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.