Can member variables be used to initialize other members in an initialization list?

半世苍凉 提交于 2019-11-27 12:05:06

This is well-defined and portable,1 but it's potentially error-prone.

Members are initialized in the order they're declared in the class body, not the order they're listed in the initialization list. So if you change the class body, this code may silently fail (although many compilers will spot this and emit a warning).


1. From [class.base.init] in the C++ standard(s):

In a non-delegating constructor, initialization proceeds in the following order:

  • First, and only for the constructor of the most derived class (1.8), virtual base classes are 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 classes in the derived class base-specifier-list.
  • Then, direct base classes are initialized in declaration order as they appear in the base-specifier-list (regardless of the order of the mem-initializers).
  • Then, non-static data members are initialized in the order they were declared in the class definition (again regardless of the order of the mem-initializers).
  • Finally, the compound-statement of the constructor body is executed.

(Highlighting is mine.)

This section of the standard then goes on to give an example of using member variables to initialize other member variables.

Yes, provide they've already been constructed. Just don't forget that the order of construction is the order of the declarations in the class definition, not the order of the initializers in the constructor. And that the compiler typically won't tell you if you use a variable before it has been constructed. In your case, for example, if you move evenSum to the top of the class, you have undefined behavior (because its initializer uses uninitialized members), even though in your constructor, you initialize evenA and evenB lexically before evenSum.

Members are initialized in the order they're declared in the class definition. As long as your initializer list follows this order, it should be ok.

This also compiled without error on g++ 4.0.3 (6 years old now).

I feel confident this will compile fine on any reasonably recent compiler.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!