C++ Reorder Warning

21 Jan 2014

If you have -Wall turned on for g++ compiler, that includes -Wreorder warning as well. What -Wreorder means is as follows:

-Wreorder (C++ only)
 Warn when the order of member initializers given in the code does not
 match the order in which they must be executed.  For instance:

 struct A {
     int i;
     int j;
     A(): j (0), i (1) { }
 };

 The compiler will rearrange the member initializers for i and j to
 match the declaration order of the members, emit-ting a warning to that
 effect.  This warning is enabled by -Wall.

Consider:

struct A {
    int i;
    int j;
    A() : j(0), i(j) { }
};

Now i is initialized to some unknown value, not zero. So this warning can actually prevent incorrect/unwanted initialization! Alternatively, the initialization of i may have some side effects for which the order is important:

A(int n) : j(n++), i(n++) { }