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

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

Program 1:

#include <iostream>
using namespace std;

class Sample {
    int A = 10;
    int B = 20;

protected:
    void print()
    {
        cout << A << " " << B;
    }
};

int main()
{
    Sample S;

    S.print();

    return 0;
}

Output:

main.cpp: In function ‘int main()’:
main.cpp:19:13: error: ‘void Sample::print()’ is protected within this context
     S.print();
             ^
main.cpp:9:10: note: declared protected here
     void print()
          ^~~~~

Explanation:

The above code will generate an error because, in the above program, we are trying to access the protected members outside the class. In C++, we can access protected members only in inheritance.

Program 2:

#include <iostream>
using namespace std;

class Sample {
};

int main()
{
    Sample S;

    cout << sizeof(S);

    return 0;
}

Output:

1

Explanation:

In the above program, we created an empty class that did not contain any members of the class.

In C++, to distinguish the object of the class, that's why the size of the empty class is 1 byte.

In the main() function, we created an object of Sample class and print the size of the object that will be 1. Then the final output will be "1" printed on the console screen.

Program 3:

#include <iostream>
using namespace std;

class Sample {
    int X;

public:
    void set(int x)
    {
        X = x;
    }
    void print()
    {
        printf("%d", X);
    }
};

int main()
{
    Sample S;

    S.set(10);
    S.print();

    return 0;
}

Output:

10

Explanation:

Here, we created a class that contains data member X and two member functions set() and print().

In the print() function, we used printf() function, but here we did not include "stdio.h" header file. To use printf() here no need to include "stdio.h" explicitly, it is automatically included in most of the C++ compiler.






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.