In C++, the order of initialization of class members always happens in the order they are declared in the class body, not in the order they are specified in the constructor's initialization list.
Example:
struct Foo { int a; int b; Foo() : b(2), a(b) {} };
In this example, a will be initialized with the value of the undefined variable b because a is initialized first, then b, regardless of the order in the initialization list. As a result, a will not be equal to 2.
The correct approach is to refer only to members that are declared above during initialization or to use constants.
In what order will class members be initialized if the initialization list order is different from their declaration?
Answer: The member that is declared first in the class is always initialized first, regardless of the order in the constructor's initialization list. This can lead to errors if members of the class are interdependent.
Story
In a complex class, during the initialization of a reference to a class member, another member was not initialized. It turned out that the order in the initialization list does not matter, resulting in the use of uninitialized memory. The software crashed only with specific compilers and settings.
Story
When adding a new member in the middle of the class without adjusting the initialization order of dependent members, an error occurred that was only detected during static code analysis. The variable took an invalid value due to the old declaration order.
Story
A new version of the library changed the class source code and altered the member order, but did not update the constructor. As a result, Values in the application were working with invalid data: the engineer couldn't understand the cause for a long time until he saw the compiler warning about the initialization order.