1 Basic virtual destructor
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 want all c ++ProgramEveryone knows this danger. Of course, if you do other work in the destructor, all your efforts will be in vain.
So,ArticleThe answer to the question at the beginning is -- this is used to call the destructor of a derived class when a base class pointer is used to delete the 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.
this article from the csdn blog, reprinted please indicate the source: http://blog.csdn.net/starlee/archive/2006/03/09/619827.aspx
in C ++, a virtual destructor is called to delete a base class pointer pointing to a derived class.