Movatterモバイル変換


[0]ホーム

URL:


UP | HOME

NOTE: class member initialization order in C++

There are some trap when usingclass in C++. One of them is theinitialization order of members. This can be annoying, therefore, I wantto record this:Declare order would affect initialization order for C++class members. For example:

classFoo {public:inti;intj = 1;Foo(): i{j} {}};

can lead to an unexpected result,i would be0 if you create aFooinstance. From reader view,j already initialized with value1,however,j wasn't initialized yet! It is hard to find out, but we onlyneed a small change to fix it:

classFoo {public:intj = 1;inti;Foo(): i{j} {}};

This is unfortunate but happened. I hope this can help to figure outwhat happened faster next time XD.

Reference tocppreference.comfor more information:

The order of member initializers in the list is irrelevant: the actualorder of initialization is as follows:

  1. If the constructor is for the most-derived class, virtual baseclasses are initialized in the order in which they appear indepth-first left-to-right traversal of the base class declarations(left-to-right refers to the appearance in base-specifier lists)
  2. Then, direct base classes are initialized in left-to-right order asthey appear in this class's base-specifier list
  3. Then, non-static data members are initialized in order of declarationin the class definition.
  4. Finally, the body of the constructor is executed
Date: 2020-04-13 Mon 00:00
Author: Lîm Tsú-thuàn

[8]ページ先頭

©2009-2025 Movatter.jp