C++ tip 5: Never call a virtual function during construction or destruction

Hi there, I want to share with you a great tip from the Efficient C++ book by Scott Meyers. It says the following:

Don't call virtual functions during construction or destruction.

Let's say that you have the following base class which has a virtual function:

class Polygon{

        //virtual method
        virtual void setArea()=0;

    //implemente the base constructor
        //call the virtual method

Now, let's say that you have the following derived class:

class Circle:public Polygon{
        //derived class constructor
        //virtual method
        virtual void setArea();

What do you think is going to happen when you create an instance of the derived class?

Circle circle;

Before the constructor of Circle is called, its base constructor Polygon is called. (Base class parts of derived class objects are constructed before derived class parts are).

The problem here is that inside the base constructor, we are calling a virtual function. In the base constructor we call a virtual method setArea(). The version of setArea() that is called is not of the derived class, but the version of the base class. I hope you see the problem. Your implementation of Circle's setArea() will not be executed.

According to Meyers:

During base class construction of a derived class object, the type of the object is that of the base class.

This means that in the beginning, all derived types are actually base types until execution of a derived class begins. In other words, in the beginning the instance circle is of type Polygon until the execution of the Circle constructor begins.

Therefore, the version of setArea() that was called was actually the version from the base class Polygon and not of the derived class Circle.

Keep this tip in mind to avoid long debugging nights: Never call virtual methods/functions in constructors or destructors.

Harold Serrano

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