ProgrammingVery hardTCS NQT Digital · Accenture Advanced

What is printed? (C++17; assume <iostream>, <string>, <vector> and using namespace std)

What is printed? (C++17; assume <iostream>, <string>, <vector> and using namespace std)
struct V { V(int x) { cout << "V" << x; } V() { cout << "V0"; } };
struct A : virtual V { A() : V(1) { cout << "A"; } };
struct B : virtual V { B() : V(2) { cout << "B"; } };
struct D : A, B { D() : V(3) { cout << "D"; } };
int main() { D d; }
  1. A. V1AV2BD
  2. B. V0ABD
  3. C. V3ABD
  4. D. V1ABD

Correct answer: C. V3ABD

The virtual base is built once, by the most derived class D with V(3); A's and B's V(1)/V(2) initializers are ignored, then A, B, D run.

More OOP with C++ and Java questions

Exams that ask this topic