Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why my virtual method is not overridden?

Tags:

c++

overriding

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?

like image 906
yoyo Avatar asked Dec 10 '10 01:12

yoyo


2 Answers

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.

like image 163
Timo Geusch Avatar answered Sep 27 '22 19:09

Timo Geusch


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

like image 40
Julio Guerra Avatar answered Sep 27 '22 18:09

Julio Guerra