C++ 析构函数 为何一般定义为虚函数,例子:
#include <iostream>
using namespace std;
class Animal
{
public:
Animal()
{
cout << "Animal::Animal() is called" << endl;
};
virtual ~Animal()
{
cout << "Animal::~Animal() is called" << endl;
}
virtual void eat()
{
cout << "Animal::eat() is called" << endl;
}
virtual void walk()
{
cout << "Animal::walk() is called" << endl;
}
/* data */
};
class Dog : public Animal
{
public:
Dog(int w,int h)
{
cout << "Dog::Dog() is called" << endl;
this->weight=w;
this->height=h;
}
virtual ~Dog()
{
cout << "Dog::~Dog() is called" << endl;
}
int weight;
int height;
void eat()
{
cout<<"i eat meat"<<endl;
}
void walk()
{
cout<<"run"<<endl;
}
/* data */
};
int main(int argc, char const *argv[])
{
/* code */
Animal *ani= new Dog(12,23);
Dog *dog=new Dog(23,34);
ani->eat();
ani->walk();
dog->eat();
dog->walk();
delete ani;
//delete dog;
return 0;
}
如果基类没有定义为虚函数,则delete ani的时候,仅仅调用了父类的析构函数,子类的没有调用,如果在父类和子类的构造函数中都有动态内存分配,那么就会存在内存泄漏的问题。一般析构函数最好都写成虚函数,尤其是父类。