1#include <iostream>2 using namespacestd;3 classA4 {5 Public:6 A ()7 {8cout<<"A Construction"<<Endl;9 } Ten Virtual~A ()//define virtual destructor causes the original destructor order to change One { Acout<<"A destructor"<<Endl; - } - the }; - classD | PublicA - { - Public: + B () - { +cout<<"B Construction"<<Endl; A } at~B () - { -cout<<"B Destruction"<<Endl; - } - - }; in classE | PublicB - { to Public : +~C () - { thecout<<"C Destruction"<<Endl; * } $ Panax Notoginseng C () - { thecout<<"C Construction"<<Endl; + } A };
the int Main (intChar *argv[]) @ +- B *b= New C; The object pointer b created by the constructor of C, this step will explain the extent of the destruction of B to the deepest of the C- delete b; $ return 0 ; *}
Output Result:
Description: The above example for the destruction of a or to a destructor B one or two of the virtual function, will be the destructor sequence from the deepest sub-class, the deepest from the creation of the object when determined, if
1#include <iostream>2 using namespacestd;3 classA4 {5 Public:6 A ()7 {8cout<<"A Construction"<<Endl;9 } Ten Virtual~A () One { Acout<<"A destructor"<<Endl; - } - the }; - classD | PublicA - { - Public: + B () - { +cout<<"B Construction"<<Endl; A } at~B () - { -cout<<"B Destruction"<<Endl; - } - - }; in classC: PublicB - { to Public : +~C () - { thecout<<"C Destruction"<<Endl; * } $ Panax Notoginseng C () - { thecout<<"C Construction"<<Endl; + } A }; the classB | PublicC + { - Public : $~D () $ { -cout<<"D Destruction"<<Endl; - } the - D ()Wuyi { thecout<<"D Construction"<<Endl; - } Wu }; - intMainintargcChar*argv[]) About { $B *b=NewC; - Deleteb; - return 0; -}
View Code
Then the output is the same as above.
C + + constructor destructor invocation order