質問

If I define a structure that inherits from multiple other structures, how does the order that I list them in affect something like this:

struct D: C,B{
    D(): B(), C(){...}
};

Simple question, but thanks in advance!

役に立ちましたか?

解決

The order of construction depends on the sequence of inheritance. Initialization order doesn't matter. GCC actually issues warning in this case.

In constructor 'D::D()':

main.cpp:16:17: warning: base 'B' will be initialized after [-Wreorder]

 D(): B(), C(){
             ^

main.cpp:16:17: warning: base 'C' [-Wreorder]

main.cpp:16:5: warning: when initialized here [-Wreorder]

 D(): B(), C(){

It is clearly specified in the standard as well. From section 12.6.2 Initializing bases and members

Initialization shall proceed in the following order:

— First, and only for the constructor of the most derived class as described below, virtual base classes shall be initialized in the order they appear on a depth-first left-to-right traversal of the directed acyclic graph of base classes, where “left-to-right” is the order of appearance of the base class names in the derived class base-specifier- list .
— Then, direct base classes shall be initialized in declaration order as they appear in the base-specifier-list (regardless of the order of the mem-initializers).

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top