C++ tip 1: How to use Virtual destructors

I read the book Effective C++ by Scott Meyers a while ago when I started the development of the engine. I learned a great deal from this book. Like everything in life, if you don't practice what you learn, you will forget it. So I decide it to read the Effective C++ book again and share what I have learned.

How to use Virtual destructors.jpg

Let's start:

Tip: Always declare a virtual destructor if and only if you also have at least one virtual method.

If you have virtual functions in a base class, make sure to declare the base's destructor virtual.

For example, listing 1 shows a base class with a virtual method and a non-virtual destructor.

Listing 1.
class Animal{
    virtual void run(); //virtual method
    ~Animal();  //non-virtual destructor
}

Now let's say that you have a derived Animal class called Monkey with a modified run method. What would happen the moment that you delete the Monkey instance?

Results are undefined when you delete a derived-class object with a non-virtual base destructor. What usually happens is that the derived class object is never destroyed. This is a great way to have memory leaks.

A simple fix to this is to make the destructor in the base class virtual as shown in listing 2.

Listing 2.
class Animal{
    virtual void run(); //virtual method
    virtual ~Animal();  //virtual destructor
}

How about when you are dealing with Abstract Classes? If you recall, Abstract classes contain Pure virtual methods. Moreover, abstract classes can't be instantiated. When dealing with abstract-classes, declare the destructor as a pure virtual method as well. This is shown in listing 3.

Listing 3.
class Animal{
    virtual void run()=0; //Pure Virtual method
    virtual ~Animal()=0;  //Pure Virtual destructor
}

Remember, pure virtual-destructor in an abstract class must provide a definition. This is shown in listing 4.

Listing 4.
Animal::~Animal(){};  //Pure Virtual destructor definition

So, if you have a polymorphic base class make sure to declare its destructor virtual.

Harold Serrano

Computer Graphics Enthusiast. Currently developing a 3D Game Engine.