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 X { string n; X(const char* s) : n(s) { cout << "+" << n; } ~X() { cout << "-" << n; } };
struct H {
    X a{"a"}; X b{"b"};
    H() : b("B"), a("A") { cout << "h"; }
    ~H() { cout << "~"; }
};
int main() { H h; }
  1. A. +B+Ah~-A-B
  2. B. +A+Bh-B-A~
  3. C. +A+Bh~-B-A
  4. D. +B+Ah~-B-A

Correct answer: C. +A+Bh~-B-A

Members are constructed in declaration order (a then b) regardless of the mem-initializer order; destruction runs the destructor body then members in reverse.

More OOP with C++ and Java questions

Exams that ask this topic