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 top开发者_运维技巧ic.
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 will Base::g()
. See this FAQ for explanation.
When your base class constructor is called, only the vtable for the base class is setup, so any virtual function calls will apply only to base class methods.
When the derived class constructor is called, calling a virtual function will call the derived class override, if any.
The virtual mechanism does not work in the constructors, so if you call even a virtual function from a base class constructor you will always end up calling the functions of the base class only. There are a few reasons why the virtual funcs do not work in the ctors:
- While in the constructors the object has not been created fully.
- ctors calls are resolved at compile time only, so they actually don't have any runtime dependency, so no use of virtual functions.
- Unlike other functions ctors and dtors are not inherited, so every class has its own set of ctors and dtors, so there is no chance of overriding.
精彩评论