Why my virtual method is not overridden?

天涯浪子 提交于 2019-12-08 21:23:51

问题


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?


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/4404978/why-my-virtual-method-is-not-overridden

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!