This question already has an answer here:
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
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
. Anyvirtual
function will be dispatched as if the object is typeC
. Likewise, when an object of a derived type is destroyed and the destructor ofC
is being run, all the derived subobjects are already destroyed and, again, the type behaves as if it is of typeC
.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.