ProgrammingVery hardProduct-company placement · C++

What is printed?

What is printed?
struct T {
    char c;
    T(char x) : c(x) { cout << c; }
    ~T() { cout << c << c; }
};
void f() { T a('a'); T b('b'); throw 1; }
int main() {
    try { T x('x'); f(); }
    catch (int) { cout << "!"; }
}
  1. A. xab!bbaaxx
  2. B. xabaabbxx!
  3. C. xabbbaaxx!
  4. D. xabbbaa!xx

Correct answer: C. xabbbaaxx!

During stack unwinding every fully constructed automatic object between the throw and the handler is destroyed in reverse order of construction: b, a (in f), then x (in the try block). Each destructor prints its letter twice; only after all three does the handler print !.

More OOP with C++ and Java questions

Exams that ask this topic