When to use virtual destructors in C++?

C++Server Side ProgrammingProgramming

Scott Meyers in Effective C++ says −

If a class has any virtual function, it should have a virtual destructor, and that classes not designed to be base classes or not designed to be used polymorphically should not declare virtual destructors.

So you should declare destructors virtual in polymorphic base classes. This is because if you create an object of base class using a derived constructor −

Base *b = new Derived();
// use b
delete b;

If Base's destructor is not virtual then delete b has undefined behavior in this case. The call to the destructor will be resolved like any non-virtual code. So the destructor of the base class will be called but not the one of the derived class, this will result in a resources leak.

Published on 28-Feb-2018 11:55:49