Say I have two base classes,
struct A {};
struct B {};
and a derived one that uses multiple inheritance
struct D : A, B {};
If my use scenario goes something like this:
A *obj = new D;
i.e. I'll never use the B
base class to refer to the derived object, do I have to make the destructor of both bases virtual? I'm currently declaring the destructor of B
as protected
to forbid other users from doing this, but is it enough?
What about the destructor of D
?
It is not necessary for B
's destructor to be virtual as long as a B*
is never used to delete derived objects. See [expr.delete]/3:
... if the static type of the object to be deleted is different from its dynamic type, the static type shall be a base class of the dynamic type of the object to be deleted and the static type shall have a virtual destructor or the behavior is undefined.
In this case the "static type" is the type T
cv where the operand to delete
has type T
cv *
. So the requirements in your case are imposed on A
, not on B
.