ProgrammingHardGATE CS · TCS NQT Prime · Product Company SDE

cpp struct A { int x = 1; }; struct B : A {}; struct C : A {}; struct D : B, C {}; int main() { D d; // d.x ? } Without virtual inheritance, what is the…

struct A { int x = 1; };
struct B : A {};
struct C : A {};
struct D : B, C {};
int main() {
    D d;
    // d.x ?
}
Without virtual inheritance, what is the problem with writing `d.x`?
  1. A. It silently refers to B's copy of x
  2. B. It is a compile error because A has no user-declared constructor
  3. C. D automatically merges the two A subobjects into one
  4. D. Ambiguous: D contains two separate A subobjects (one via B, one via C), so d.x does not know which to use without qualifying it as d.B::x or d.C::x

Correct answer: D. Ambiguous: D contains two separate A subobjects (one via B, one via C), so d.x does not know which to use without qualifying it as d.B::x or d.C::x

Non-virtual inheritance gives D two independent A base subobjects, so an unqualified d.x is ambiguous and must be written d.B::x or d.C::x.

More OOP with C++ and Java questions

Exams that ask this topic