ProgrammingHardProduct-company placement · C++

What is printed?

What is printed?
struct M { M(const char* s) { cout << s; } };
struct S {
    M x, y;
    S() : y("Y"), x("X") { cout << "S"; }
};
int main() { S s; }
  1. A. YXS
  2. B. SXY
  3. C. SYX
  4. D. XYS

Correct answer: D. XYS

Members are always initialised in the order they are DECLARED in the class (x, then y), whatever order the initializer list is written in; the constructor body runs last. Compilers only warn about the mismatch.

More OOP with C++ and Java questions

Exams that ask this topic