In the case of single inheritance , the parent class is constructed before the subclass, and the subclass is destructor before the parent class, for example:
classA { Public: A () {cout<<"A"<<Endl; } ~A () {cout<<"~a"<<Endl; }};classD | PublicA { Public: B () {cout<<"B"<<Endl; } ~B () {cout<<"~b"<<Endl; }};
The result is:
AB~B~a
In the case of multiple inheritance, the construction order of the two sibling parent classes arises when the order of construction satisfies the requirement of the single inheritance construction order. At this time, for sibling parent classes, the construction order is based on the inheritance list from left to right. The destructor sequence is reversed.
classA { Public: A () {cout<<"A"<<Endl; } ~A () {cout<<"~a"<<Endl; }};classb{ Public: B () {cout<<"B"<<Endl; } ~B () {cout<<"~b"<<Endl; }};classC: PublicB PublicA { Public: C () {cout<<"C"<<Endl; } ~C () {cout<<"~c"<<Endl; }};
Output:
BAC~C~A~b
Class contains Class objects in the context of the construction order:
classA { Public: A () {cout<<"A"<<Endl; } ~A () {cout<<"~a"<<Endl; }};classD | PublicA { Public: B () {cout<<"B"<<Endl; } ~B () {cout<<"~b"<<Endl; }};classC: PublicB PublicA { Public: C () {cout<<"C"<<Endl; } ~C () {cout<<"~c"<<Endl; }};classD: PublicB { Public: D () {cout<<"D"<<Endl; } ~D () {cout<<"~d"<<Endl; }Private: c C; A;};
The output is:
A //BA / / defines the object of C, the first of the C inheritance order is b,b inherits a, so is a, BBA // the second in the C inheritance order C / /C definition a // D in Parameters ad~d~A~ C~a~b~a~b~a
In-class declarations :
class D { public : D ( int A) {cout << d: " << a << Endl; }}; class M { public : M () {cout << m " << Endl; extern D D; }};
The above notation does not error, because there is no definition of the object, only the object declaration. Therefore, you do not need to call the constructor of D.
Contains the static variable :
class m {public: m () { 'm' << Endl; } Private: static d D;};
Without the definition of a static object, the definition of the M object is not an error, because the constructor of class D is not used. That is, d only made a declaration that was not defined.
Construct the member order in multiple sections :
classA { Public: A () {cout<<"A"<<Endl; } ~A () {cout<<"~a"<<Endl; }};classb{ Public: B () {cout<<"B"<<Endl; } ~B () {cout<<"~b"<<Endl; }};classD {Private: A; b b; Public: D () {cout<<"D"<<Endl; } ~D () {cout<<"~d"<<Endl; }Private: B B2; A A2;};
Output Result:
ABBAD~D~A~b~b~a
Just like the code above, regardless of the Exchange access area or access rights, it is always constructed in order from top to bottom.
The construction Order of C + + classes