C++ Quiz23 of 173
Difficulty:
⬅️ Prev: 28Quiz ID: 29Next: 30 ➡️

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

#include <iostream>

struct A {
  A() { foo(); }
  virtual ~A() { foo(); }
  virtual void foo() { std::cout << "1"; }
  void bar() { foo(); }
};

struct B : public A {
  virtual void foo() { std::cout << "2"; }
};

int main() {
  B b;
  b.bar();
}
Hint

Are there times when virtual functions are not considered virtual?

Reveal answer

121

Explanation

Even though foo() is virtual, it is not considered to be so during the execution of constructors and destructors.

Rationale:

If an object of type B is being constructed, first the constructor of A is called, then the constructor of B. Thus, during A's constructor, the "B part" of the object has not been constructed yet, and should not be used. One could easily imagine that B::foo() would use the "B part" of the object, so it would be dangerous for A's constructor to call it.

When the object is destroyed, B's destructor is called first, then A's destructor, leading to the same problem.

⬅️ Prev: 28Quiz ID: 29Next: 30 ➡️