ProgrammingHardHCL · Tech Mahindra pattern

What is printed?

What is printed?
struct A { A() { cout << "A"; } ~A() { cout << "~A"; } };
struct B { A a; B() { cout << "B"; } ~B() { cout << "~B"; } };
int main() {
    B *p = new B();
    delete p;
}
  1. A. ABB~~A
  2. B. AB~B~A
  3. C. AB~A~B
  4. D. BA~A~B

Correct answer: B. AB~B~A

B's member a (type A) constructs before B's own constructor body, so it prints A then B. On deletion, B's destructor body runs first (~B), and only afterward are its members destroyed, in reverse declaration order: a's destructor runs last, printing ~A. Result: AB~B~A.

More OOP with C++ and Java questions

Exams that ask this topic