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 for Derived::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.
Because you wrote it like that... Your call to the derived class constructor does:
- Base Class Constructor call
|
Call to **fun of Base Class**
- Derived Class Constructor call
|
Call to **fun of the Derived Class**
More details here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With