Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
547 views
in Technique[技术] by (71.8m points)

c++ - Calling virtual function of derived class from base class constructor?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...