|
Order, Order! |
First, the most derived class's constructor calls the constructors of the virtual base class subobjects. Virtual base classes are initialized in depth-first, left-to-right order. | |
Next, direct base class subobjects are constructed in the order they are declared in the class definition. | |
Next, (nonstatic) member subobjects are constructed, in the order they were declared in the class definition. | |
Finally, the body of the constructor is executed. |
For example, consider the following code. Whether the inheritance is public, protected, or private doesn't affect initialization order, so I'm showing all inheritance as public.
// Example 2
//
class B1 { };
class V1 : public B1 { };
class D1 : virtual public V1 { };
class B2 { };
class B3 { };
class V2 : public B1, public B2 { };
class D2 : public B3, virtual public V2 { };
class M1 { };
class M2 { };
class X : public D1, public D2 { M1 m1_; M2 m2_; };
The inheritance hierarchy looks like this:
B1 B1 B2
| | /
| | /
| | /
V1 V2 B3
| | /
|v v| /
| | /
D1 D2
\ /
\ /
\ /
X
The initialization order for a X object in Example 2 is as follows, where each constructor call shown represents the execution of the body of that constructor:
first, construct the virtual bases:
construct V1:
B1::B1()
V1::V1()
construct V2:
B1::B1()
B2::B2()
V2::V2()
next, construct the nonvirtual bases:
construct D1:
D1::D1()
construct D2:
B3::B3()
D2::D2()
next, construct the members:
M1::M1()
M2::M2()
finally, construct X itself:
X::X()
This should make it clear why in Example 1 it's illegal to call either A::f() or the s member subobject's construct.
Of course, although the main point of this issue of GotW was to understand the order in which objects are constructed (and, in reverse order, destroyed), it doesn't hurt to repeated a tangentially related guideline:
Guideline: Avoid overusing inheritance.
Except for friendship, inheritance is the strongest relationship that can be expressed in C++, and should be only be used when it's really necessary. For more details, see also:
The updated material in Exceptional C++ and More Exceptional C++ |
Copyright © 2009 Herb Sutter |