Example 5.1
Analyze the order in which destructors and constructors are called in the following program.
1#include <iostream>2 3 using namespacestd;4 5 class Object6 {7 Private:8 intVal;9 Public:Ten Object(): Val (0) One { Acout <<"Ddfault constructor for object"<<Endl; - } - Object(inti): Val (i) the { -cout <<"Constructor for Object"<< Val <<Endl; - } -~Object() + { -cout <<"destructor for Object"<< Val <<Endl; + } A }; at - classContainer - { - Private: - ObjectOne//The initialization order is related to the order in which the object members are generated - Objectboth;//first initialization in the front row in intdata; - Public: toContainer ():d ATA (0) + { -cout <<"Ddfault constructor for object"<<Endl; the } *ContainerintIintJintk); $~container ()Panax Notoginseng { -cout <<"destructor for Object"<< Data <<Endl; the } + }; A theContainer::container (intIintJintk): II (i), one (j)//independent of initialization list order + { -data =K; $cout <<"Constructor for Container"<< Data <<Endl; $ } - - voidMain () the { -Container obj, Anobj (5,6,Ten);Wuyi theSystem"Pause"); -}
Example 5.2
Analyze the output of the following program.
123
C + + Programming _ Chapter 5th _ Special functions and members