Look at the code first:
1#include <iostream>2 using namespacestd;3 4 classParent {5 Public:6Parent (): A ( -), B ( $), C ( -)7 {8 9p =New Char[Ten];Ten //strcpy (P, "abc"); Onecout <<"Parent Non-parametric construction ... \ n"; A } -Parent (intTest): A ( +), B ( -), C ( the) - { thep =New Char[Ten]; - //strcpy (P, "abc"); -cout <<"parent has a parameter structure ... \ n"; - } +~Parent () - { + Delete[] p; Acout <<"Parent Destruction ... \ n"; at } - intA; - intb; - intC; - Char*p; - voidP_print () in { -cout <<"a b c is"<< a <<" "<< b <<" "<< C <<Endl; to } + - }; the classChild1: PublicParent * { $ Public:Panax NotoginsengChild1 ():P arent (1), A (Ten), B (0), C (0) - { thep =New Char[Ten]; + //strcpy (P, "abc"); Acout <<"child1 construction \ n"; the } +~Child1 () - { $ Delete[] p; $cout <<"child1 destruction,, \ n"; - } - voidC1_print () the { -cout <<"a b c is"<< a <<" "<< b <<" "<< C <<Endl;Wuyi } the - intA; Wu intb; - intC; About Char*p; $ }; - classChild2: PublicChild1 - { - Public: AChild2 (): Child1 (), B (2), C (3) + { thep =New Char[Ten]; - //strcpy (P, "abc"); $cout <<"child2 construction \ n"; the } the~Child2 () the { the Delete[] p; -cout <<"child2 destruction,, \ n"; in } the voidC2_print () the { Aboutcout <<"a b c is"<< parent::a <<" "<< b <<" "<< C <<Endl; the } the //int A; the intb; + intC; - Char*p; the };Bayi /* the class Child3:public Child1, public Child2 the { - Public : - Child3 (): Child1 (), Child2 (), B (d), C (+) {cout << "child construction \ n";} the ~child3 () the { the cout << "Child destructor,, \ n"; the } - void C3_print () the { the cout << "A b c is" << a << "<< b <<" "<< c << Endl; the }94 //int A; the int b; the int C; the };98 */ About voidPlay () - {101child2* C2 =NewChild2;102 Delete C2;103 }104 intMain () the {106 //child2* c2 = new Child2;107 play ();108 return 0;109}
This is fine, but, in many cases, we cannot delete this memory at the end of the call function, and we need to interact with it later, so the more common and general design thinking is to change the paly and main functions as follows:
1 voidPlay (parent*p)2 {3 Deletep;4 }5 intMain ()6 {7child2* C2 =NewChild2;8 Play (C2);9 return 0;Ten}
The running results show that the memory leaks, only the parent class is analyzed; so we have a need, like polymorphic effects, what pointers to go, automatic destruction should be the destruction of things, change the code, implement virtual destructor.
Just change the destructor of the base class, plus the virtual keyword:
1 virtual ~Parent ()2 {3 Delete[] p; 4 " Parent Destruction ... \ n"; 5 }
So there's no memory leak.
Just briefly:
C + +--Virtual destructor