Pure virtual function call in constructor

Pure virtual functions must not be called from a C++ constructor.

As a general rule, you should never call any kind of virtual function in a constructor or destructor because those calls will never go to a more derived class than the currently executing constructor or destructor. In this case, the function being called is a pure virtual function, meaning that no implementation is provided in the class itself. Since it has no implementation, this call cannot be resolved and the program will fail to link.

It may seem that the call would be resolved to virtual function definition corresponding to the derived class that is being created. The reason this cannot be done is because the derived class has not yet been initialized. The base class constructor is called before the constructor of the derived class.

ID

Observation

Description

1

Call site

This shows where the virtual function was called

2

Definition

This shows where the constructor was defined

Example


#include <stdio.h>

class A
{
public:
    A() {
        intermediate_call();
    }

    void intermediate_call() {
        // Bad: virtual function call during object construction
        virtual_function();
    }

    virtual void virtual_function() = 0;

    virtual ~A() {
    }
};

class B : public A
{
public:
    // override virtual function in A
    void virtual_function()
    {
        printf("B::virtual_function called\n");
    }
};

int main(int argc, char **argv)
{
    A *myObject;

    // Call to virtual_function during construction doesn't
    // behave like normal virtual function call.
    // Program will attempt to call pure virtual function
    // Since no defintion exists, program will either fail
    // to link or fail catastrophically at run time.
    myObject = new B();

    delete myObject;
}
        

Copyright © 2011, Intel Corporation. All rights reserved.