虚函数调用在构造函数和析构函数中 [英] virtual function calls in constructor and destructor

查看:150
本文介绍了虚函数调用在构造函数和析构函数中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

    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;
     }

有什么想法为什么这个代码打印出base br>
我理解的建议不是把虚函数调用放在构造函数或者析构函数中,我只是想知道为什么上面的代码会有行为。感谢

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

推荐答案

在执行类 C 的构造函数期间,派生子对象尚未构建。因此,正在构造的对象的动态类型是构造函数的静态类型,即 C 。任何 virtual 函数将被分派,如同对象是类型 C 。同样,当一个派生类型的对象被销毁,并且正在运行 C 的析构函数时,所有派生的子对象都已经被销毁,是 C 类型。

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.

这篇关于虚函数调用在构造函数和析构函数中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆