virtual function calls in constructor and destruct

2019-01-15 22:58发布

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

1条回答
不美不萌又怎样
2楼-- · 2019-01-15 23:53

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.

查看更多
登录 后发表回答