ProgrammingHardMicrosoft/Amazon SDE MCQ · GATE CS

What is printed?

What is printed?
struct P { const char* s; P(const char* s) : s(s) { cout << s; } ~P() { cout << "~" << s; } };
struct B { P b{"B"}; };
struct D : B {
    P y, x;
    D() : x("X"), y("Y") { }
};
int main() { D d; }
  1. A. BXY~Y~X~B
  2. B. BYX~B~Y~X
  3. C. BYX~X~Y~B
  4. D. YXB~B~X~Y

Correct answer: C. BYX~X~Y~B

Bases are built first (B's member prints B), then members in DECLARATION order, y then x, whatever the initializer list says. Destruction is the exact reverse: ~X, ~Y, then the base's ~B.

More OOP with C++ and Java questions

Exams that ask this topic