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;
}- 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
- B. s.a is 1 and s.b is reliably 2, because the initializer list runs a(1) before b(a+1)
- C. This fails to compile because the initializer list order (a, b) doesn't match declaration order (b, a)
- 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
- What is printed? java class A { protected int val() { return 1; } } class B extends A { protected int val() { return 2; } } class C…
- A Java class's constructor runs this.handle = acquire(); and then later throws an exception before returning. Which statement is correct?
- What is printed? cpp struct N { int v; N(int x) : v(x) { std::cout << "N" << v << " "; } ~N() { std::cout << "~N" << v << " "; } }; int…
- What is printed? java class A { public String toString() { return "A"; } } class B extends A { public String toString() { return "B-" +…
- What is printed? java class Box<T> { T value; } // in main: Box<String> b1 = new Box<>(); Box<Integer> b2 = new Box<>()…
- What is printed (assume typical compiler codegen)? cpp struct Base { ~Base() { cout << "~Base "; } }; struct Derived : Base { int buf =…