I've got a solid knowledge of most OO theory however the one factor that atmosphere us a lot is virtual destructors.

I figured the destructor always will get known as regardless of what as well as for every object within the chain.

When are you currently meant to ensure they are virtual and why?

Virtual destructors are helpful when you are able manipulate a clear case of a derived class via a pointer to base class:

class Base


class Derived : public Base

Here, you'll find that I did not declare Base's destructor to become virtual. Now, let us take a look in the following snippet:

Base *b = new Derived()

// use b

remove b // Here's the issue! Since Base's destructor isn't virtual,

          // it's ~Base that's known as and never ~Derived. Therefore, all of the important

          // cleanup isn't carried out, which could create several resource leaks

To summarize, always make base classes' destructors virtual when they are intended to be altered polymorphically.

If you wish to avoid the deletion of the instance via a base class pointer, you may make the bottom class destuctor protected and nonvirtual in so doing, the compiler will not allow you to call remove on the base class pointer.

Discover more about virtuality and virtual base class destructor in this short article from Plant Sutter.

Declare destructors virtual in polymorphic base classes. This really is Item 7 in Scott Meyers' Effective C++. Meyers continues in summary when a category has any virtual function, it will possess a virtual destructor, which classes not made to be base classes or otherwise designed for use polymorphically should not declare virtual destructors.

Check this out: Virtual Destructor

Result in the destructor virtual once your class is polymorphic.

Also remember that removing basics class pointer when there's no virtual destructor can lead to undefined behavior. Something which I learned just lately:


I have used C++ for a long time and that i still have the ability to hang myself.