2014-10-27 70 views
0

下面是我試圖理解輸出的代碼。派生類析構函數發生了什麼?

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類? 對象切片在這裏發揮作用嗎?

回答

5

你需要讓父類的析構函數虛:

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