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?- A. The compiler reorders the actual initialisation to match the list, with a warning only
- B. It fails to compile because the initializer-list order must match declaration order
- 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
- 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
- What does List<? super Integer> allow, in contrast to List<? extends Integer>?
- java try { throw new ArithmeticException("x"); } catch (RuntimeException e) { System.out.print("R"); } catch (ArithmeticException e) {…
- Which OOP principle bundles data with the methods that act on it and hides the internal state behind an interface?
- In Java, which keyword makes one class inherit from another class?
- What is the return type of a C++ constructor?
- Every Java class that declares no superclass implicitly extends: