Consider the following C++ code. Which statement is correct?
#include <iostream>
using namespace std;
class Base {
private:
int x = 10;
protected:
int y = 20;
};
class Derived : public Base {
public:
void display() {
cout << y;
}
};
int main() {
Derived d;
d.display();
return 0;
}
Options
-
A.
The program prints 10.
-
B.
The program prints 20.
-
C.
The program fails because Derived cannot access y.
-
D.
More than one of the above
-
E.
None of the above
Correct Answer (Detailed Explanation is Below)
B.
The program prints 20.
Detailed Explanation
Correct Answer: Option BExplanation:Derived cannot directly access the private member x, but it can access the protected member y. The display() function prints
20. This illustrates the difference between private and protected members during inheritance.