大家知道,析構函式是為了在物件不被使用之後釋放它的資源,虛函式是為了實現多型。那麼把析構函式宣告為vitual有什麼作用呢?請看下面的**:
#includeusing namespace std;
class base
; //base的建構函式
~base() //base的析構函式
; virtual void dosomething()
;};class derived : public base
; //derived的建構函式
~derived() //derived的析構函式
; void dosomething()
;};int main()
先看程式輸出結果:
1 do something in class derived!
2 output from the destructor of class derived!
3 output from the destructor of class base!
4 5 do something in class derived!
6 output from the destructor of class base!
**第36行可以正常釋放ptest1的資源,而**第42行沒有正常釋放ptest2的資源,因為從結果看derived類的析構函式並沒有被呼叫。通常情況下類的析構函式裡面都是釋放記憶體資源,而析構函式不被呼叫的話就會造成記憶體洩漏。原因是指標ptest2是base型別的指標,釋放ptest2時只進行base類的析構函式。在**第8行前面加上virtual關鍵字後的執行結果如下:
1 do something in class derived!
2 output from the destructor of class derived!
3 output from the destructor of class base!
4 5 do something in class derived!
6 output from the destructor of class derived!
7 output from the destructor of class base!
此時釋放指標ptest2時,由於base的析構函式是virtual的,就會先找到並執行derived類的析構函式,然後再執行base類的析構函式,資源正常釋放,避免了記憶體洩漏。
因此,只有當乙個類被用來作為基類的時候,才會把析構函式寫成虛函式。
virtual析構函式
當派生類物件撤銷時,一般先呼叫派生類的析構函式,然後再呼叫基類的析構函式。include using namespace std class base class derived public base int main void 執行結果 呼叫基類base的析構函式 如果在主函式中用new運算子建...
析構函式virtual與非virtual區別
析構函式virtual與非virtual區別 作為通常的原則,如果乙個類定義了虛函式,那麼它的析構函式就應當是virtual的。因為定義了虛函式則隱含著 這個類會被繼承,並且會通過基類的指標指向子類物件,從而得到多型性。這個類可能會被繼承,並且會通過基類的指標指向子類物件 因此基類的析構函式是否為虛...
基類加析構函式加virtual的重要性
例子 include include include using namespace std class per1 public per1 cout create per1 create per1 create per2 exit per2 delete p exit per1 不加virtual的...