Home »
C++ programming »
C++ find output programs
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.