liveBook · Manning

Virtual destructor

A virtual destructor is a destructor whose dynamic dispatch ensures that destroying an object through a base-class interface invokes the derived-class destructor.

How 2 Manning books explain it

100 C++ Mistakes and How to Avoid Them

A virtual destructor is a destructor declared virtual so destruction through a base-class interface dispatches to the derived object's destructor.

How it is used
Protects cleanup when polymorphic objects are deleted through base-class pointers or stored in containers.
How deep it goes
Explains the rule, demonstrates undefined behavior and leakage, and contrasts failing and corrected destruction output.
Examples
Uses Shape and Square resource cleanup plus Person and Employee objects in polymorphic containers.
What you can do after
Diagnose/debug leaks from base-pointer deletion and correct polymorphic base classes with virtual destructors.

Read how 100 C++ Mistakes and How to Avoid Them explains virtual destructor →

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.

How it is used
Enables safe cleanup when polymorphic objects are accessed and deleted through base-class pointers.
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 you can do after
Apply it by declaring a defaulted virtual destructor in a polymorphic base class before deleting derived objects through base pointers.

Read how Learn C++ by Example explains virtual destructor →

Related concepts

These guides are generated from the text of Manning books by Manning's knowledge graph and link to the sections they draw on. The full books are available on liveBook and at manning.com.