轉載一片博客:
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