liveBook · Manning

Virtual destructor

As explained in Learn C++ by Example

A virtual destructor is a destructor declared virtual so that deleting an object through a base-class pointer invokes the appropriate derived-class destructor.

A virtual destructor lets polymorphic deletion through a base-class pointer call the derived-class destructor first, followed by the base-class destructor. Without it, deleting a derived object through a base pointer has undefined behavior. section 6.1.1

Safe cleanup for race blobs

A Blob base class can declare `virtual ~Blob() = default;`. Then `Blob* blob = new DerivedBlob(); delete blob;` performs the complete destruction sequence. The same declaration supports a hierarchy of blob types while retaining a base-class pointer interface. section 6.1.1

How Learn C++ by Example covers it

How deep it goes
Explains destructor dispatch, undefined behavior, and v-table placement, then stops short of detailed implementation mechanics.
Examples
Uses a Blob and DerivedBlob race hierarchy to contrast base-pointer deletion with derived-pointer deletion.
What it assumes
Assumes familiarity with classes, inheritance, pointers, and virtual functions while illustrating the deletion hazard concretely.
What you can do after
Apply it by declaring a defaulted virtual destructor in a polymorphic base class before deleting derived objects through base pointers.
How it connects
Connects virtual destructors with polymorphism, virtual functions, base classes, derived classes, v-tables, and smart pointers.

Also explained in

Compare how 2 books explain virtual destructor →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn C++ by Example. The section links point to the parts of the book it draws on.