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.