ProgrammingHardProduct-company MCQ pattern

What happens when this is compiled?

What happens when this is compiled?
struct A { int x; };
struct B : A {};
struct C : A {};
struct D : B, C {};
int main() {
    D d;
    d.x = 5;
}
  1. A. Compiles; d.x refers to the single shared A::x
  2. B. Compile-time error: d.x is ambiguous, because D has two separate A subobjects (via B and via C)
  3. C. Compiles; d.x refers to B::x by default since B is listed first
  4. D. Runtime error: ambiguous member access

Correct answer: B. Compile-time error: d.x is ambiguous, because D has two separate A subobjects (via B and via C)

Without virtual inheritance, D contains two independent A subobjects, one inherited through B and one through C, each with its own x. Writing d.x does not say which one is meant, so the compiler rejects it as ambiguous; it would need d.B::x or d.C::x.

More OOP with C++ and Java questions

Exams that ask this topic