For the class inheritance/initialization of member variables/constructor/destructor execution sequence, see the following code:
# Include <iostream> <br/> using namespace STD; </P> <p> Class A {<br/> Public: <br/> () {cout <"A" <Endl ;}< br/> ~ A () {cout <"~ A "<Endl ;}< br/>}; </P> <p> Class B {<br/> Public: <br/> B () {cout <"B" <Endl ;}< br/> ~ B () {cout <"~ B "<Endl ;}< br/> PRIVATE: <br/> A; <br/>}; </P> <p> Class C: Public, public B {<br/> Public: <br/> C () {cout <"C" <Endl ;}< br/> ~ C () {cout <"~ C "<Endl ;}< br/> Public: <br/> A; <br/> PRIVATE: <br/> B; <br/> }; </P> <p> int main () {<br/> C * Pc = new C (); <br/> Delete PC; <br/> return 0; <br/>}
The output of the above Code is as follows:
A
A
B
A
A
B
C
~ C
~ B
~ A
~ A
~ B
~ A
~ A
A: When initializing a subclass, initialize the parent class in the same sequence as the inheritance class. In this example, initialize A, B, and C.
B: during class initialization, The Address Allocation and initialization of the member variables are performed before the constructor. The initialization sequence of the member variables (by the compiler) is the same as the declared sequence.
C: the order of object analysis is opposite to that of the execution constructor.
In the code above, C inherits a and B, and B calls. therefore, when declaring the C object, initialize a first. Because a does not have a variable declaration, execute the constructor directly and output "".
Then initialize B. Because member variable A is declared in B, initialize a first, and execute the constructor of A to output "A"; then execute the constructor of B, output "B ".
After the parent class is initialized, initialize the member variables of C, which are a A and B in the Declaration Order. so initialize a first, output "A", then initialize B, output "A" and "B", then execute the constructor of C, output "C ", therefore, the final output result is:
The destructor of aabaabc is opposite. The output is :~ C ~ B ~ A ~ A ~ B ~ A ~ A.
If A and B are declared as variables in Class C, the output result is:
A
A
B
A
B
A
C
~ C
~ A
~ B
~ A
~ B
~ A
~ A