派生类析构函数发生了什么?

时间:2014-10-27 18:23:06

标签: c++ visual-c++

以下是我试图理解输出的代码。

class A
    {
    public:

        A();
        ~A(){ cout<<"Destructor Called from A"<<endl;}
        A(int x):Z(x){ cout<<"Constructor Called from A"<<endl; };

    private:
        int Z;
    };

    class B:public A
    {
    public:

        B();
        ~B(){ cout<<"Destructor Called from B"<<endl;}
        B(int x):A(x),Y(x){ cout<<"Constructor Called from B"<<endl; };

    private:
        int Y;
    };

    int main() {

        A *a = new B(10);        
        delete a;

        return 0;
    }

我将输出作为

Constructor Called from A
Constructor Called from B
Destructor Called from A

我的问题是,类B的析构函数发生了什么? 对象切片是否在这里发挥作用?

1 个答案:

答案 0 :(得分:5)

您需要将超类的析构函数设为虚拟:

 class A {
    virtual ~A(){ cout<<"Destructor Called from A"<<endl;}