Why C + + destructors are generally defined as virtual functions, examples:
#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::D og () 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; }
If the base class is not defined as a virtual function, then the delete ANI only calls the destructor of the parent class, the subclass is not invoked, and if there is dynamic memory allocation in the constructor of the parent class and subclass, then there is a memory leak problem. A general destructor is best written as a virtual function, especially a parent class.