Contents Up << >>

When should my destructor be virtual?

When you may "delete" a derived object via a base pointer.

Virtual fns bind to the code associated with the class of the object, rather than with the class of the pointer/ref. When you say "delete basePtr", and the base class has a virtual destructor, the destructor that gets invoked is the one associated with the type of the object *basePtr, rather than the one associated with the type of the pointer. This is generally A Good Thing.

To make life easy for you, the only time you wouldn't want to make a class's destructor virtual is if that class has no virtual fns, since the introduction of the first virtual fn imposes some space overhead in each object (typically one machine word). This is how the compiler implements the magic of dynamic binding; it usually boils down to an extra ptr per object called the "virtual table pointer" or "vptr".