1 //Study of Virtual destructor function2 //If an external program uses the new operator to define a dynamic object, the delete operator is used to delete the dynamic object when the external program ends.3 //However, if the external program takes advantage of the assignment compatibility principle, assigns the address of the derived class object of the dynamic request to the base class object pointer, because the delete operator implies the automatic invocation of the destructor4 //so at this point the system automatically calls the destructor of the base class, which can cause a memory leak problem5 //The following is an example of a virtual destructor6#include <iostream.h>7#include <string.h>8 9 classa{Ten Public: One A () {} A //~a () { - //cout<< "base class destructor" <<endl; - // } the - Virtual~A () { -cout<<"base class destructor"<<Endl; - } + - }; + A classAa: Publica{ at Private: - Char*AA; - intlength; - Public: -AA (Char*message) { -Length=strlen (message) +1; inAa=New Char[length]; - strcpy (aa,message); to } +~AA () { - DeleteAA; thecout<<"derived class destructor"<<Endl; * } $ Panax Notoginseng }; - the intMain () { +A *pa=NewAA ("Hello"); A DeletePA; the return 0; + } - $ //illustrated by This example $ //whenever a useful operator in a constructor of a derived class or other member function of a derived class new dynamically requests memory space, the destructor of its base class must be designed as a virtual destructor
C + + Learning (24)