C + + Virtual destructor:
Virtual destructor
(1) The virtual destructor is the definition of the Declaration destructor before the virtual modification, if the destructor of the base class is declared as a virtual destructor,
The destructor for all derived classes derived from the base class is also automatically a virtual destructor.
(2) Base class pointer pbase to a derived class object created with new dynamically child, with "delete pbase;" There are two cases of deleting objects:
First, if the destructor in the base class is a virtual destructor, the derived class object is deleted before the base class object is deleted
Second, if the destructor in the base class is a non-virtual destructor, only the base class object will be deleted, and the derived class object will not be deleted, so there is a memory leak
#include <iostream>using namespacestd; #include<string>//////////////////////////// classBase { Public:#if0Virtual~base ();//In Child::~child () in Base::~base ()#else~base (); // in Base::~base () risk of memory leaks #endif}; Base::~Base () {cout<<"In base::~base ()"<<Endl;}////////////////////////////classChild: PublicBase { Public: ~Child ();}; Child::~Child () {cout<<"In child::~child ()"<<Endl;}intDemo () { Base *PC =NewChild ; cout<<"-----------"<<Endl; Delete pc; cout<<"-----------"<<Endl; return 0 ;}intMain () {demo (); while(1); return 0;}
C + + virtual destructor [avoid memory leaks]