C++ Question – Can you have a virtual destructor?

Can you have a virtual destructor?

Yes, and if you have a base class, then it should have a virtual destructor.  The scenario where virtual destructors are needed is:

User allocates derived class instance using new() and assigns it to a pointer variable of the base class.

NonVirtualDestructor* c = new DerivedNonVirtualDestructor();
delete c;

In this situation, when delete is called, the destructor for the NonVirtualDestructor class will be called, but not the destructor for the DerivedNonVirtualDestructor class.  This could cause havoc if the DerivedNonVirtualDestructor class is expecting its destructor to always be called (e.g. to free previously allocated resources).  See item 14 in Effective C++ by Meyers for a more detailed explanation of why you should always make sure base classes have virtual destructors.

Here is a gist demonstrating virtual destructors, and the pitfall described above.

Posted in C++