Tuesday, May 27, 2008

c++: virtual functions in contructors

There is a limitation on virtual function calls in constructors. If you call a virtual function in the constructor of the base class that was overridden in derived class you will be surprised. The function of base class will be called:

class A
{
    public:
        A() {function();}
        virtual void function() {cout << "A" << endl;}
};

class B : public A
{
    public:
        B() {function();}
        virtual void function() {cout << "B" << endl;}
};

int
main(int argc,
    char **argv)
{

    B b;

    return 0;
}
This code produces
A
B
output. The explanation is pretty simple, when constructor of the base class is called the derived object has not been constructed. This way c++ protects us. You don't have access to the derived class object from the the base class constructor. Only when initialization of base class was had been finished virtual table is being refreshed.

No comments: