一,为什么基类的析构函数是虚函数呢?
在实现多态时,当一个类被作为基类并且该基类对派生类的对象进行操作,在析构时防止只析构基类而不析构派生类的状况发生。把基类的析构函数设计为虚函数可以在基类的指针指向派生类对象时,用基类的指针删除派生类对象,避免内存泄漏。
二,通过几个例子来看一下效果
1,例子1:
#include<iostream>
using namespace std;
class Base {
public:
Base() {};
~Base() { cout << "Output from the destructor of class Base!" << endl; };
void DoSomething() { cout << "Do something in class Base!" << endl; };
};
class Derived : public Base {
public:
Derived() {};
~Derived() { cout << "Output from the destructor of class Derived!" << endl; };
void DoSomething() { cout << "Do something in class Derived!" << endl; };
};
void main() {
Derived *p = new Derived;
p->DoSomething();
delete p;
return;
}