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 G { const char* n; G(const char* s) : n(s) {} ~G() { cout << n; } };
void f() { G a("a"); G b("b"); throw 1; }
int main() {
    try { G c("c"); f(); }
    catch (int) { cout << "X"; }
    cout << "Y";
}
  1. A. abcXY
  2. B. cbaXY
  3. C. bacXY
  4. D. XbacY

Correct answer: C. bacXY

Stack unwinding destroys f's locals in reverse (b, a), then c in the try block, before the handler prints X; execution continues with Y.

More OOP with C++ and Java questions

Exams that ask this topic