virtual destructor
In C++, the constructor cannot be defined as a fictitious constructor, because the constructor is called only when an object is instantiated, and the implementation of the virtual function is actually called through a virtual function table pointer, and there is no object update. Of course it cannot be called without memory space, so the fictitious constructor before instantiating an object is meaningless and cannot be implemented.
However, destructors can be virtual functions, and most of the time they are declared as virtual destructors. In this way, when the object of the derived class pointed to by the base class pointer is released, the destructor of the subclass can be dynamically compiled and called according to the actual object type pointed to, so as to achieve the correct object memory release.
Let's do an experiment below, please look at the code:
/************************************//Des: C++ tutorial demo//Author: Huang//Copyright:www.dotcpp.com//Date:2017/12/27********************************** *******/#include<iostream>usingnamespacestd;classPoint{private:intx,y;int*str;public:Point(intx=0,inty=0){this->x=x;this-> y=y;str=newint[100];}~Point(){delete[]str;cout<<CalledPoint'sDestructorandDeletedstr!<<endl;}};classCircle:publicPoint{private:intr;int*str;public: Circle(intx,inty,intR):Point(x,y){r=R;str=newint[100];}~Circle(){delete[]str;cout<<CalledCircle'sDestructorandDeletedstr!<<endl;} };intmain(){Point*p;p=newCircle(10,10,20);deletep;return0;}
You can see the code. There is no destructor declared with virtual in the base class, and both the base class and the derived class have dynamic memory allocation. Then we create a Circle class in the main function by dynamically allocating memory, and then delete it. The screenshot after running is as follows:
It can be clearly seen that only the destructor of the base class is called, so that the 4*100 bytes of new memory in the derived class will remain, causing a memory leak!
And if the destructor in the base class is declared as virtual, the result will be very different! At this time, the polymorphic effect appears. It will first release the space of the derived class, and then release the memory space of the base class. It ends perfectly, as shown below:
Above, these are the benefits brought by the virtual destructor, you can experience it yourself.