ProgrammingVery hardGATE CS · TCS Digital · Advanced

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

What is printed? (C++17, assume <iostream> and using namespace std)
struct M {
    const char* n;
    M(const char* s) : n(s) { }
    ~M() { cout << n; }
};
struct B {
    M m{"b"};
    ~B() { cout << "B"; }
};
struct D : B {
    M x{"x"};
    M y{"y"};
    ~D() { cout << "D"; }
};
int main() { D d; }
  1. A. BbDyx
  2. B. DyxBb
  3. C. DxyBb
  4. D. DBbxy

Correct answer: B. DyxBb

Destruction runs in the reverse of construction: D's body, then D's members in reverse declaration order (y, x), then the base B (its body, then its member b).

More OOP with C++ and Java questions

Exams that ask this topic