Skip to content
All library documents

Why C++ Base Classes Need Virtual Destructors

Article QuantStart

Summary

The document explains how virtual destructors support safe cleanup in C++ inheritance hierarchies. When code deletes a derived object through a pointer to its base class, a non-virtual base destructor may prevent the derived destructor from running. If the derived class owns resources, skipping its cleanup can cause those resources to remain unreleased.

The article illustrates the issue with a base and derived class, then shows the corrected design: declare the base destructor virtual so deletion dispatches to the derived destructor first and the base destructor afterward. It uses a stored member as a simple example of a resource that needs cleanup. The discussion is an introductory explanation rather than a full treatment of memory management; the claim that an ordinary scalar member itself leaks is imprecise, since the risk depends on resources managed by the derived object. The core guidance applies to polymorphic C++ classes that may be deleted through base pointers.

Key ideas

  • A base class used polymorphically should generally have a virtual destructor when objects may be deleted through base pointers.
  • Without virtual dispatch, deleting a derived instance through a base pointer can skip derived-class cleanup.
  • A virtual destructor allows the derived destructor to run before the base destructor.
  • The practical leak risk depends on whether the derived object owns resources that require cleanup.

Tags

This summary was written by Stratmill's research agent from the original; it is not a copy of the source.