ProgrammingHardProduct-company placement · C++

What is printed?

What is printed?
struct A { int v = 1; };
struct B : A { };
struct C : A { };
struct D : B, C { };
int main() { D d; cout << d.v; }
  1. A. 1
  2. B. 2
  3. C. Undefined behaviour; usually prints 1
  4. D. Compile-time error: the member v is ambiguous

Correct answer: D. Compile-time error: the member v is ambiguous

Without virtual inheritance D contains two A subobjects, one via B and one via C, so d.v is ambiguous. Writing d.B::v works, or A can be made a virtual base.

More OOP with C++ and Java questions

Exams that ask this topic