ProgrammingVery hardIBM · Deloitte pattern

Which statement about this program's behaviour is true?

Which statement about this program's behaviour is true?
struct S {
    int b;
    int a;
    S() : a(1), b(a + 1) { }
};
int main() {
    S s;
    std::cout << s.a << " " << s.b;
}
  1. A. s.a is reliably 1, but s.b is indeterminate: members initialize in declaration order (b before a), so b(a+1) read a's pre-construction value
  2. B. s.a is 1 and s.b is reliably 2, because the initializer list runs a(1) before b(a+1)
  3. C. This fails to compile because the initializer list order (a, b) doesn't match declaration order (b, a)
  4. D. Both s.a and s.b are indeterminate because initializer lists never guarantee any order

Correct answer: A. s.a is reliably 1, but s.b is indeterminate: members initialize in declaration order (b before a), so b(a+1) read a's pre-construction value

Members always initialize in declaration order, not initializer-list order. b is declared before a, so b(a+1) runs first and reads a before a(1) has executed — b's value is indeterminate even though the code compiles and a ends up reliably 1.

More OOP with C++ and Java questions

Exams that ask this topic