ProgrammingHardGATE 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 R {
    const char* n;
    R(const char* s) : n(s) { cout << "+" << n; }
    ~R() { cout << "-" << n; }
};
void f() {
    R a("a");
    throw 1;
    R b("b");
}
int main() {
    try {
        R c("c");
        f();
    } catch (int) {
        cout << "X";
    }
    cout << "Y";
}
  1. A. +c+a-a-cXY
  2. B. +c+a-aX-cY
  3. C. +c+a-a-cYX
  4. D. +c+a-c-aXY

Correct answer: A. +c+a-a-cXY

Unwinding destroys fully constructed automatic objects in reverse order of construction (a, then c) before the handler runs; b is never constructed because the throw precedes it.

More OOP with C++ and Java questions

Exams that ask this topic