You must never call virtual functions within a constructor.
Virtual functions don't get dispatched the way you think they do. Rather, during construction, the dynamic type of the base subobject that is being constructed is the base type, and thus the function is dispatched to the base function (which is pure-virtual in your case).
Just don't do it.
(The reason is obvious: When constructing a derived object, the base subobject must necessarily be constructed first, so the ambient derived object doesn't even exist at the time of the base construction.)
Edit: Here's some more explanation. Compilers are perfectly allowed and encouraged to perform virtual dispatch statically if they can do so. In that case, it is determined at compile time already which actual function will be called. This happens when you say foo()
or this->foo()
in the Base
constructor, or when you say x.Base::foo()
in some other context where Derived x;
is your object. When the dispatch happens statically, then either the implementation of Base::foo()
is called directly, or you get a linker error if there is no implementation.
On the other hand, if the dispatch happens dynamically, i.e. at runtime, then there is a possibility, albeit unusual, that the dispatch actually ends up picking Base::foo()
as the final target. This cannot happen under "normal" conditions, because the compiler won't let you instantiate a class with pure-virtual functions, and so the target of an ordinary dynamic dispatch is always a function for which an implementation must exist (or at least you'd get a linker error if you don't link it).
But there is one more situation, which is the one in question: The compiler decides to perform the dispatch at runtime, for whatever reason, and the dipatch ends at a pure-virtual function. In that case your program terminates. It is irrelevant whether the function is implemented or not, but is simply doesn't have an entry in the polymorphic class hierarchy (think of it as a "null pointer in the vtable", hence the = 0
). For this to happen, the dynamic type of the object must be the type of an abstract base class, and the dispatch has to happen dynamically. The former can only be achieved inside the base constructor of a derived object, and the latter requires you to convince the compiler not to dispatch the call statically. This is where the difference between this->foo()
(static) and Base * p = this; p->foo();
(dynamic) comes in. (Also contrast this to x.Base::foo()
, which is dispatched statically.)
All this is merely a consequence of the implementation and covered by the blanket "undefined behaviour", of course. If you want to take one thing away from it, then it is that dynamic dispatch cannot find a pure-virtual function. And of course that you must never call virtual functions within a constructor.
this->foo()
works whereas calling via the cast fails. – Buckish