Skip to content

When a destructor must be virtual

Question

What is a virtual destructor, and in which situations do you need one?

Short answer

A destructor declared virtual so that deleting through a base pointer runs the derived destructor first. Without it, delete basePtr on a derived object is undefined behaviour and in practice skips derived cleanup, leaking resources. Any class meant to be used polymorphically (typically one with virtual functions) should have a public virtual destructor.

Adapted from Joshi, Denson & Downes, Quant Job Interview Questions and Answers, Q7.12, p.226; question and answer rewritten by SelfMadeQuant.com.

See the hint and the full worked solution in the question bank (free account).

Open the worked solution

Lessons behind this question