virtual function calls in constructor and destructor [duplicate]
Asked Answered
B

1

0
    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

Bigeye answered 2/9, 2013 at 21:8 Comment(1)
Actually, it outputs "basederivedderivedbase" (after fixing //main), and if you think about it for awhile, you'll see why.Sclar
P
4

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.

Progeny answered 2/9, 2013 at 21:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.