What happens when a derived class directly accesses a private member of its base class?
#include <iostream>
using namespace std;
class Base
{
private:
int x = 5;
};
class Derived : public Base
{
public:
void show()
{
cout << x;
}
};
int main()
{
Derived d;
d.show();
return 0;
}
Options
-
A.
It prints 5
-
B.
It prints 0
-
C.
Compilation error because x is private in Base
-
D.
More than one of the above
-
E.
None of the above
Correct Answer (Detailed Explanation is Below)
C.
Compilation error because x is private in Base
Detailed Explanation
Correct Answer: Option CExplanation:Private members belong to the base class and cannot be accessed directly by derived-class member functions. The expression
cout << x therefore causes a compilation error. A public or protected base-class function could provide controlled access.