C++ Quiz14 of 173
Difficulty:
⬅️ Prev: 14Quiz ID: 15Next: 16 ➡️

According to the C++23 standard, what is the output of this program?

#include <iostream>
#include <exception>

int x = 0;

class A {
public:
  A() {
    std::cout << 'a';
    if (x++ == 0) {
      throw std::exception();
    }
  }
  ~A() { std::cout << 'A'; }
};

class B {
public:
  B() { std::cout << 'b'; }
  ~B() { std::cout << 'B'; }
  A a;
};

void foo() { static B b; }

int main() {
  try {
    foo();
  }
  catch (std::exception &) {
    std::cout << 'c';
    foo();
  }
}
Hint

When are static local variables initialized? If an exception is thrown in a constructor, is the object considered constructed? Will the destructor be called?

Reveal answer

acabBA

Explanation

Static local variables are initialized the first time control passes through their declaration. The first time foo() is called, b is attempted to be initialized. Its constructor is called, which first constructs all member variables. This means A::A() is called, resulting in the printing of 'a.' However, A::A() then throws an exception; consequently, the constructor is aborted, and neither b nor B::a are actually considered constructed. In the catch block, 'c' is printed, and then foo() is called again. Since b was never successfully initialized the first time, it tries again, this time succeeding, which leads to 'ab' being printed. When main() exits, the static variable b is destroyed. This process first calls the destructor, which prints 'B,' and then destroys the member variables, indicated by the printing of 'A'.

⬅️ Prev: 14Quiz ID: 15Next: 16 ➡️