从基类构造函数调用派生类的虚函数? [英] Calling virtual function of derived class from base class constructor?

查看:222
本文介绍了从基类构造函数调用派生类的虚函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图完成上一个问题中所述的相同操作:



基类的虚函数调用



但是,我真正的问题是:



如果f()是Base类的构造函数怎么办?将调用哪个g()?我不知道我是否做错了,但在我的程序中,似乎是相反的。



从上一个问题取相同的变量,代码显示此类



行为如下所示:

  

{

Base(){g();};

virtual void g(){//做一些基本相关的代码;}

};



类派生类型:public Base

{

Derived(){};

virtual void g(){//做一些派生相关代码};

};



int main()

{

派生newDerived;

return 0;

}

更新: >

Thanx到Naveen。



他提供了一个页面,其中包含关于此主题的所有相关信息。



我会告诉您这里的连结:



parashift.com/c ++ - faq-lite / strange-inheritance.html#faq-23.6


I´m trying to accomplish the same which is described in a previous question:

virtual function call from base class

But, my real question is:

What if f() is the constructor in the Base class? Which g() will be called? I don´t know if I am doing wrong, but in my program it seems to be that is the opposite.

Taking the same variables from the previous question, a code which shows such

behavior would look like this:

Class Base

{   

    Base(){g();};

    virtual void g(){//Do some Base related code;}

};



Class Derived : public Base

{   

    Derived(){};

    virtual void g(){//Do some Derived related code};

};



int main()

{

    Derived newDerived;

    return 0;  

}

Update:

Thanx to Naveen.

He provided me a page which contains all related information about this topic.

I´ll let you know the link here:

parashift.com/c++-faq-lite/strange-inheritance.html#faq-23.6

解决方案

Even though it's a virtual function, the base's version will get called since the derived class isn't fully constructed yet. The base class constructor is called before the derived class constructor, so if the derived virtual function were to get called, it would be with an incompletely-initialized instance - a possible (probably) recipe for disaster.

这篇关于从基类构造函数调用派生类的虚函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆