Parsing the function of virtual destructor in C + + _c language

Source: Internet
Author: User
We know when developed in C + +, the destructor of the class used to do the base class is usually a virtual function. But why do you do it? Here is a small example to illustrate:
There are two classes below:
Copy Code code as follows:

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
Copy Code code as follows:

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

The output results are:
Do something in class clxderived!
Output from the destructor of class clxderived!
This is very simple, very good understanding.
However, if you remove the virtual before the class Clxbase destructor, the output is the following:
Do something in class clxderived!
In other words, the destructor of the class clxderived is not invoked at all! In general, the class's destructor is free of memory resources, and the destructor is not invoked to create a memory leak. I think all C + + programmers are aware of this danger. Of course, if you do something else in the destructor, all your efforts are futile.

So the answer to the question at the beginning of the article is to do this so that when you delete an object of a derived class with a pointer to a base class, the destructor of the derived class is invoked.

Of course, not all class destructors are written as virtual functions. Because when there is a virtual function in the class, the compiler adds a virtual function table to the class that holds the virtual function pointer, which increases the storage space of the class. Therefore, the destructor is written as a virtual function only when a class is used as a base class.

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.