下面的內容要說明兩個問題:1. 基類的析構函數爲何要加上Virtual--防止內存泄露函數
1. 基類虛構函數無virtual,派生類沒法析構,會致使內存泄露blog
#include <stdio.h> class Base { public: int a; Base(){ a=0; } ~Base(){ printf("base delete"); } virtual void setA()=0; }; class A:public Base { public: A(){ a = 10; } ~A(){ printf("A class delete\n"); } virtual void setA() { a = 2; } }; class B:public Base { public: B(){ a=20; } ~B(){ a=-20; } virtual void setA() { a = 3; } }; int main() { Base *ax = new A(); Base *bx = new B(); Base *aClass = ax; Base *bClass = bx; printf("a value of a construct %d\n", aClass->a); printf("a value of b construct %d\n", bClass->a); aClass->setA(); bClass->setA(); printf("a value of a %d\n", aClass->a); printf("a value of b %d\n", bClass->a); delete aClass; return 0; }
運行結果爲:內存
2. 若在基類析構函數前加上Virtualio
class Base { public: int a; Base(){ a=0; } virtual ~Base(){ printf("base delete"); } virtual void setA()=0; };
運行結果爲:class