C++类继承--基类析构函数加上Virtual
下面的内容要说明两个问题:1. 基类的析构函数为什么要加上Virtual--防止内存泄露
1. 基类虚构函数无virtual,派生类无法析构,会导致内存泄露
#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. 若在基类析构函数前加上Virtual
class Base { public: int a; Base(){ a=0; } virtual ~Base(){ printf("base delete"); } virtual void setA()=0; };
运行结果为: