class Base
{
public:
Base()
{
cout<<"base class"<<endl;
fun();
}
virtual void fun(){cout<<"fun of base"<<endl;}
};
class Derive:public Base
{
public:
Derive()
{
cout<<"derive class"<<endl;
fun();
}
void fun(){ cout<<"fun of derive"<<endl;}
};
void main()
{
Derive d;
}
The output is:
base class
fun of base
derive class
fun of derive
Why the second line is not fun of derive?
When you call
fun()in the base class constructor, the derived class has not yet been constructed (in C++, classes a constructed parent first) so the system doesn’t have an instance of Derived yet and consequently no entry in the virtual function table forDerived::fun().This is the reason why calls to virtual functions in constructors are generally frowned upon unless you specifically want to call the implementation of the virtual function that’s either part of the object currently being instantiated or part of one of its ancestors.