ProgrammingHardWipro · Cognizant pattern

What is printed?

What is printed?
struct X {
    int id;
    X(int i) : id(i) { std::cout << "X" << id << " "; }
    ~X() { std::cout << "~X" << id << " "; }
};
struct Y {
    X x1{1}, x2{2}, x3{3};
};
int main(){ Y y; }
  1. A. X1 X2 X3 ~X3 ~X2 ~X1
  2. B. X1 X2 X3 ~X1 ~X2 ~X3
  3. C. X3 X2 X1 ~X1 ~X2 ~X3
  4. D. X1 X2 X3 ~X2 ~X1 ~X3

Correct answer: A. X1 X2 X3 ~X3 ~X2 ~X1

Members construct in declaration order (x1, x2, x3) and are destroyed in the exact reverse order when y goes out of scope, regardless of how they are used elsewhere.

More OOP with C++ and Java questions

Exams that ask this topic