Why is my virtual method not overridden?

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; } 

Output:

 base class fun of base derive class fun of derive 

Why is the second line not fun of derive ?

+6
c ++ override
source share
2 answers

When you call fun() in the constructor of the base class, the derived class is not yet constructed (in C ++, the constructed parent is created first), therefore, the system does not yet have an Derived instance and, therefore, does not have an entry in the virtual function table for Derived::fun() .

This is why calls to virtual functions in constructors are usually disapproved unless you specifically want to call an implementation of a virtual function that is either part of the object that is currently being created or part of one of its ancestors.

+4
source share

Because you wrote it like this ... Your call to the constructor of the derived class:

 - Base Class Constructor call | Call to **fun of Base Class** - Derived Class Constructor call | Call to **fun of the Derived Class** 

More here

+2
source share

All Articles