for a single class, the destructor is not a virtual function, it has no substantive meaning. However, when the current class is a base class, the destructor of the base class is not a virtual function, which affects the program in varying degrees. look at the following code to run the result:
#include <iostream>using namespace Std;class base{public:base () {cout << "Base:constructor" <<ENDL;} ~base () {cout << "base:destructor" << Endl;}}; Class Deriveda:public Base{public:deriveda () {cout << "Deriveda:constructor" <<ENDL;} ~deriveda () {cout << "deriveda:destructor" << Endl;}}; Class Derivedb:public Deriveda{public:derivedb () {cout << "Derivedb:constructor" <<ENDL;} ~derivedb () {cout << "Derivedb:destructor" <<endl;}}; int main () {base* tmp = new Deriveda ();d elete Tmp;return 0;}
The result of the operation is:
running results as you can see, when the destructor is a non-virtual function, delete tmp only calls the destructor of the base class, and does not call the derived class's destructor. the destructor for the base class below uses a virtual destructor to try the result:
#include <iostream>using namespace Std;class base{public:base () {cout << "Base:constructor" <<ENDL;} Virtual ~base () {cout << "base:destructor" << Endl;}}; Class Deriveda:public Base{public:deriveda () {cout << "Deriveda:constructor" <<ENDL;} ~deriveda () {cout << "deriveda:destructor" << Endl;}}; Class Derivedb:public Deriveda{public:derivedb () {cout << "Derivedb:constructor" <<ENDL;} ~derivedb () {cout << "Derivedb:destructor" <<endl;}}; int main () {base* tmp = new Deriveda ();d elete Tmp;return 0;}
The result of the operation is:
At this point, when the function calls delete tmp, the destructor of the derived class is called first, and then the destructor of the base class is called.
normally, in a destructor of a class, there is always some work to be done to free up memory resources, and when the destructor is not called correctly, it is possible that the memory that should be freed is not released at the end of the program, thus causing a memory leak. When the amount of data is large, it can cause a great loss. And for a C + + programmer, always ensure that the program does not appear memory leaks, so that we must always pay attention to the problem. To sum up, when we need to use the current class as the base class, we must pay attention to the destruction of the destructor of the processing. Of course, when we do not do the base class, we can not set the virtual destructor.
The use of virtual functions in the summary of C + + programming