ProgrammingVery hardProduct-company placement · C++

What is printed?

What is printed?
struct A { A(int x) { cout << x; } A() { cout << 0; } };
struct B : virtual A { B() : A(1) { cout << "B"; } };
struct C : virtual A { C() : A(2) { cout << "C"; } };
struct D : B, C { D() : A(3) { cout << "D"; } };
int main() { D d; }
  1. A. 1BCD
  2. B. 12BCD
  3. C. 0BCD
  4. D. 3BCD

Correct answer: D. 3BCD

A virtual base is constructed exactly once, by the MOST derived class, before any non-virtual base. D's A(3) is used and the A(...) initialisers in B and C are ignored.

More OOP with C++ and Java questions

Exams that ask this topic