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
{< br> Public :< br> clxderived () {};
~ clxderived () {cout " output from the destructor of class clxderived! " Endl ;};
VoidDosomething () {cout< "Do something in class clxderived!" <Endl ;};
};
Code
Clxbase * Ptest = New Clxderived;
Ptest -> Dosomething ();
DeletePtest;
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 clxderived is not called at all! in general, all class destructor release memory resources. If the Destructor is not called, memory leakage occurs. I think all c ++ Program Members know this danger. Of course, if you do other work in the destructor, all your efforts will be in vain.
SO, the answer to the question starting with Article is -- to delete an object of A derived class with a base class pointer, the destructor of the derived class is called.
Of course, not all class destructor should be written 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.