ProgrammingVery hardProduct company interview · GATE level

What is printed?

What is printed?
struct A { int v = 0; A() { cout << "A"; } };
struct B : A { B() { cout << "B"; } };
struct C : A { C() { cout << "C"; } };
struct D : B, C { D() { cout << "D"; } };
int main() {
    D d;
    d.B::v = 5;
    cout << " " << d.C::v;
}
  1. A. ABCD 5
  2. B. ABACD 0
  3. C. ABCD 0
  4. D. ABACD 5

Correct answer: B. ABACD 0

Without virtual inheritance, D contains two separate A subobjects, one inside B and one inside C, so A's constructor runs twice: A B A C D. Writing through B's copy leaves C's copy at 0. An unqualified d.v would not even compile, because it is ambiguous. Declaring B and C with virtual A would give a single shared A, print ABCD and make both paths show 5.

More OOP with C++ and Java questions

Exams that ask this topic