Consider abstract class AbstractMap and it's child classMyMap.
Is it safe to perform the following delete operation?
ptr = static_cast<AbstractMap*>(new MyMap());
delete ptr;
Deleting through a pointer to base sub object can be safe only if the destructor of the base (AbstractMap
in this case) is virtual. If that precondition isn't satisfied, then the behaviour of the program is undefined.
Suppoes AbstractMap has a virtual destructor, how can it call the child class's destructor?
Note that if you created the instance using allocating new expression, then you aren't supposed to call the destructor directly. delete
will do that for you.
But in the special cases where you may need to call the destructor directly, you do it by calling the destructor of AbstractMap
using dynamic dispatch (which is the default form of dispatch for virtual functions).
how can it know that the "original" one is MyMap?
You don't need to know the dynamic type. That's what makes virtual functions so great.
P.S. Avoid owning bare pointers. There's hardly ever a need to write new
and delete
.