virtual function calls in constructor and destructor

1.1k views Asked by At
    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

There are 1 answers

0
Dietmar Kühl On

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.