基類和派生類析構函數執行順序


轉載一片博客:

http://www.cnblogs.com/dongling/p/5864295.html

 

下面是自己實驗結果:

沒有聲明虛函數時:

#include <iostream>
using namespace std;

class Base
{
public:
    Base()
    {
        cout<<"Base contruction"<<endl;
    }
     ~Base()
    {
        cout<<"Base deconstruction"<<endl;
    }

};

class Derived: public Base
{
public:
    Derived(int i)
    {
        num = i;
        cout<<"Derived contruction "<<num<<endl;
    }
     ~Derived()
    {
        cout<<"Derived deconstruction"<<num<<endl;
    }

};

int main()
{
    Derived derived(1);

    Base* basePtr;
    Derived* derevedPtr;
    
    basePtr = new Derived(2);
    
    delete basePtr;
    
    


}

輸出:

Base contruction
Derived contruction 1
Base contruction
Derived contruction 2
Base deconstruction
Derived deconstruction1
Base deconstruction
跟上面博文實驗結果一致

總結:
由上面的實驗結果可以看出,當 new CDerive() 時,會先運行基類的構造函數,然后再運行派生類的構造函數;
而當 delete pointer 時,編譯器只考慮 pointer 指針本身的類型而不關心 pointer 實際指向的類型,即:若 pointer 為基類指針,則只調用基類的析構函數(不管 pointer 實際指向的是基類還是派生類);若 pointer 是派生類指針,則先調用派生類的析構函數,再調用基類的析構函數,調用順序與調用構造函數的順序相反。

在聲明虛函數之后:

#include <iostream>
using namespace std;

class Base
{
public:
    Base()
    {
        cout<<"Base contruction"<<endl;
    }
    virtual ~Base()
    {
        cout<<"Base deconstruction"<<endl;
    }

};

class Derived: public Base
{
public:
    Derived(int i)
    {
        num = i;
        cout<<"Derived contruction "<<num<<endl;
    }
    virtual ~Derived()
    {
        cout<<"Derived deconstruction"<<num<<endl;
    }

};

int main()
{
    Derived derived(1);

    Base* basePtr;
    Derived* derevedPtr;
    
    basePtr = new Derived(2);
    
    delete basePtr;
    
    


}

輸出:

Base contruction
Derived contruction 1
Base contruction
Derived contruction 2
Derived deconstruction2
Base deconstruction
Derived deconstruction1
Base deconstruction


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM