MiddleCodeRareNot answered yet
What does this member initializer list print?
Predict the output — watch the order in the initializer list.
struct S {
int a;
int b;
S(int x) : b(x), a(b) {} // note the order written here
};
int main() { S s(5); std::cout << s.a << " " << s.b; }
Determine the output and explain.
s.b is 5, but s.a is garbage. Members initialize in declaration order (a then b), not the order written in the initializer list, so a(b) runs first and reads b before it is set. Compile with -Wreorder to catch this.
- ✗Believing the initializer-list order drives initialization
- ✗Expecting a compile error rather than a read of an uninitialized member
- ✗Not knowing
-Wreorderwarns about a list/declaration mismatch
- →Why does the standard fix initialization to declaration order?
- →What exactly does
-Wreorderwarn about?