简体   繁体   中英

In what ways does C++ inheritance order affect a constructor?

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM