ProgrammingVery hardGATE CS · TCS NQT Prime · Product Company SDE

cpp struct S { int a, b; S(int x) : b(x), a(b) { } }; int main() { S s(5); cout << s.a << " " << s.b; } Members a and b are declared in that order (a, then…

struct S {
    int a, b;
    S(int x) : b(x), a(b) { }
};
int main() {
    S s(5);
    cout << s.a << " " << s.b;
}
Members a and b are declared in that order (a, then b). What actually happens, regardless of the order written in the initializer list?
  1. A. The compiler reorders the actual initialisation to match the list, with a warning only
  2. B. It fails to compile because the initializer-list order must match declaration order
  3. C. Members initialise in their declaration order (a first, then b), so a(b) reads b's still-uninitialised, indeterminate value: a ends up garbage while b correctly becomes 5
  4. D. Members initialise exactly in the order written in the list (b first, then a), so a correctly receives 5 too

Correct answer: C. Members initialise in their declaration order (a first, then b), so a(b) reads b's still-uninitialised, indeterminate value: a ends up garbage while b correctly becomes 5

C++ always initialises base/member subobjects in their declaration order, never the order written in the member-initializer list, so writing b(x), a(b) still initialises a before b and a ends up reading an indeterminate value.

More OOP with C++ and Java questions

Exams that ask this topic