Dec 17, 2008

What happens when a Constructor gives a call to a virtual functions

What happens when a Constructor gives a call to a virtual functions

you shouldn't call virtual functions from a constructor because the vtable has not yet been setup at instantiation.
from MSDN: “When a virtual method is called, the actual type that executes the method is not selected until run time. When a constructor calls a virtual method, it is possible that the constructor for the instance that invokes the method has not executed“.
reference:
http://www.artima.com/cppsource/nevercall.html


class base
{
public:
base()
{
cout<<"I am in base::base()"<<endl;
foo();
}
virtual void foo(){cout<<"I am in base::foo()"<<endl;}
};

class derived:public base
{
public:
derived()
{
cout<<"I am in derived::derived()"<<endl;
}
void foo(){cout<<"I am in derived::foo()"<<endl;}
};


int main(void)
{
derived d;
}

The output is:
I am in base::base()
I am in base::foo()
I am in derived::derived()



No comments:

Post a Comment