I was writing some code today and got a weird compile error, which seems to be caused by initializing member variables in a different order than they were declared.
Example:
class Test {
int a;
int b;
public:
Test() : b(1), a(2) {
}
};
int main() {
Test test;
return 0;
}
Then if I compile it with -Werror -Wall
:
$ g++ -Werror -Wall test.cpp
test.cpp: In constructor ‘Test::Test()’:
test.cpp:3:9: error: ‘Test::b’ will be initialized after [-Werror=reorder]
test.cpp:2:9: error: ‘int Test::a’ [-Werror=reorder]
test.cpp:6:5: error: when initialized here [-Werror=reorder]
cc1plus: all warnings being treated as errors
I realize that -Wall
is explicitly asking GCC to go over-the-top with warnings, but I assume there's a reason for all of them. So, how could the order of initializing member variables matter?
The reason is because they're initialized in the order they're declared in your class, not the order you initialize them in the constructor and it's warning you that your constructor's order won't be used.
This is to help prevent errors where the initialization of b
depends on a
or vice-versa.
The reason for this ordering is because there is only one destructor, and it has to pick a "reverse order" to destroy the class member. In this case, the simplest solution was to use the order of declaration within the class to make sure that attributes were always destroyed in the correct reverse order.