Role of virtual destructor in C ++

Source: Internet
Author: User

From: http://blog.csdn.net/starlee/archive/2006/03/09/619827.aspx

 

We know that the Destructor used for base classes during C ++ development are generally virtual functions. But why? Here is a small example:
There are two classes:

Class clxbase
{
Public:
Clxbase (){};
Virtual ~ Clxbase (){};

Virtual void dosomething () {cout <"do something in class clxbase! "<Endl ;};
};

Class clxderived: Public clxbase
{
Public:
Clxderived (){};
~ Clxderived () {cout <"output from the destructor of class clxderived! "<Endl ;};

Void dosomething () {cout <"do something in class clxderived! "<Endl ;};
};

Code

Clxbase * Ptest = new clxderived;
Ptest-> dosomething ();
Delete Ptest;

The output result is:

Do something in class clxderived!
Output from the destructor of class clxderived!

This is very easy to understand.
However, if you remove the virtual before the clxbase destructor, the output result is as follows:

Do something in class clxderived!

That is to say, the destructor of the class clxderived is not called at all! Under normal circumstances, all the class destructor release the memory resources, and if the Destructor is not called, memory leakage will occur. I think all c ++ programmers know this danger. Of course, if you do other work in the destructor, all your efforts will be in vain.
Therefore, the answer to the question at the beginning of the article is -- This is to call the destructor of a derived class when a base class pointer is used to delete an object of A derived class.

Of course, it is not necessary to write all class destructor as virtual functions. When there is a virtual function in the class, the compiler will add a virtual function table to the class to store the virtual function pointer, which will increase the storage space of the class. Therefore, only when a class is used as the base class can the Destructor be written as a virtual function.

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.