ProgrammingModerateCapgemini · TCS NQT

What happens when this C++ program is compiled?

What happens when this C++ program is compiled?
struct B { int x = 5; };
class D : B { };
int main() { D d; cout << d.x; }
  1. A. Prints 5
  2. B. Compile error: x is inaccessible because class D inherits B privately
  3. C. Prints 0
  4. D. Compiles but crashes at run time

Correct answer: B. Compile error: x is inaccessible because class D inherits B privately

Inheritance defaults to private for class, so B's public member x becomes private in D and cannot be accessed from main.

More OOP with C++ and Java questions

Exams that ask this topic