Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...