Puzzle #2 (based on N4296)

#include <iostream>

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

struct A : B
{
  virtual void foo() = 0;
};

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

struct D : A
{
  void foo() override
  {
    std::cout << "D";
  }
};

int main()
{
  B b;
  D d;
  b.foo();
  d.foo();
}

With given code, pick one answer:

  • Guaranteed to print “AA”
  • Guaranteed to print “AB”
  • Guaranteed to print “AD”
  • Guaranteed to print “BA”
  • Guaranteed to print “BB”
  • Guaranteed to print “BD”
  • Guaranteed to print “DA”
  • Guaranteed to print “DB”
  • Guaranteed to print “DD”
  • Undefined behavior
  • Implementation defined
  • Will not compile
Click here for the answer

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

There are two things that may be (or may not) strange to you:

  • A pure virtual method definition.
  • A pure virtual method overriding.

Both of them are well defined in the standard.

A pure virtual method can be defined but it must be defined outside of the class body

10.4.2 (Note)

A function declaration cannot provide both a pure-specifier and a definition

  1. And about the overriding:

10.4.5

(…) a pure virtual function may override a virtual function which is not pure.

Thanks for reading o/