Why C + + destructors are generally defined as virtual functions __jquery

Source: Internet
Author: User

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.


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.