ProgrammingVery hardProduct company interview · GATE level

What is printed?

What is printed?
struct P  { P(const char* s) { cout << s; } };
struct B1 { B1() { cout << "1"; } };
struct B2 { B2() { cout << "2"; } };
struct X : B2, B1 {
    P a, b;
    X() : b("b"), a("a"), B1(), B2() { cout << "X"; }
};
int main() { X x; }
  1. A. ba12X
  2. B. 21abX
  3. C. 12abX
  4. D. 12baX

Correct answer: B. 21abX

The order of a member-initialiser list is irrelevant. Bases are initialised in the order they are listed in the class head (B2, then B1), and members in the order they are declared in the class (a, then b), and only then does the constructor body run. Compilers usually warn about the misleading initialiser order, but the output is fixed: 2 1 a b X.

More OOP with C++ and Java questions

Exams that ask this topic