Always make base class destructor as virtual in C++

TLDR: The title of this post says it all!

If you are having a class hierarchy, with base class and derived classes, then try to always make the base class destructor as virtual.

I recently noticed an application having a serious memory leak after merging some code. Other than the leak, everything else about the code was executing fine! After debugging the code, the culprit turned out to be a base class destructor that was not virtual. If only the above rule had been followed diligently, the error would have been caught easily.

Why this rule? The reason for this rule is pretty simple. A derived class destructor might be deallocating objects or freeing memory that it had allocated earlier during its creation or execution. Now think about the scenario where this derived class object is held using a base class pointer and it is freed.

  • If base class destructor is not virtual: Only the base class destructor is called, thus causing a memory leak.

  • If base class destructor is virtual: The derived class destructor is called first (thus freeing its allocated objects correctly) before the trail of destruction heads up the chain of hierarchy, ending in the base class destructor. This is the intended correct behavior.

Here is a code example that illustrates this scenario: