问题
class Base
{
public:
Base(){Foo();}
~Base(){Foo();}
virtual void Foo(){std::cout<<"base";}
};
class Derived: public Base
{
public:
Derived(){Foo();}
~Derived(){Foo();}
void Foo(){std::cout<<"derived";}
};
//main
{
Derived d;
}
Any idea why this code prints out "base" and "derived"?
I understand the advice is not to put virtual function calls inside constructor or desctructor, I just want to know why the above code would have the behaviour. Thanks
回答1:
During execution of the constructor of a class C
, the derived subobjects are not, yet, constructed. Thus, the dynamic type of the object under construction is the static type of the constructor, i.e., C
. Any virtual
function will be dispatched as if the object is type C
. Likewise, when an object of a derived type is destroyed and the destructor of C
is being run, all the derived subobjects are already destroyed and, again, the type behaves as if it is of type C
.
That is, during construction and destruction the type of an object involving inheritance changes! The dynamic dispatch is arranged to match the current type of the object.
来源:https://stackoverflow.com/questions/18580779/virtual-function-calls-in-constructor-and-destructor