You cannot call a pure virtual function from the constructor. At the time the constructor is running, the object is considered to be of the type being constructed, not of any derived type. Which means virtual dispatch "stops" at the type being constructed.
This means that calling fill()
from the constructor of a
will try to call a::fill()
, regardless of any derived classes of which this a
subobject can be part. And this of course fails miserably, since the function has no implementation.
Additionally, as @KerrekSB points out, your class needs a virtual destructor. Otherwise, you will get undefined behaviour if you ever delete
a b
instance via a pointer to a
(which is quite likely when shared_ptr<a>
is involved).
UPDATE Apparently, shared_ptr
is capable of using the default deleter properties to work around the necessity for a virtual destructor, so your class is technically OK not having one. Still, without a virtual destructor, you class depends on being managed in std::shared_ptr
s only; if you ever change that bit of design, you will run into trouble (and it will not be immediately obvious). I therefore suggest having a virtual destructor anyway.