Puzzle #3 (based on N4296)

#include <iostream>
struct A
{
  A() {
    foo();
  }

  ~A() {
    foo();
  }

  void foo() const {
    std::cout << "0 ";
  }

  void foo() {
    std::cout << "1 ";
  }
};

int main() {
    const A a;
    a.foo();
}

With given code, pick one answer:</br>

  • Guaranteed to print “000”.
  • Guaranteed to print “001”.
  • Guaranteed to print “010”.
  • Guaranteed to print “011”.
  • Guaranteed to print “100”.
  • Guaranteed to print “101”.
  • Guaranteed to print “110”.
  • Guaranteed to print “111”.
  • Undefined behavior.
  • Implementation defined.
  • Will not compile.
Click here for the answer

The correct answer is: Guaranteed to print “101”..

Answer seems to be tricky, but after a while it becomes obvious.

12.1.3

A constructor can be invoked for a const, volatile or const volatile object. const and volatile semantics (7.1.6.1) are not applied on an object under construction. They come into effect when the constructor for the most derived object (1.8) ends.

And similar for the destructor:

12.4.2

A destructor can be invoked for a const, volatile or const volatile object. const and volatile semantics (7.1.6.1) are not applied on an object under destruction. They stop being in effect when the destructor for the most derived object (1.8) starts.

Thanks for reading o/