ProgrammingHardAccenture · Cognizant pattern

What is printed?

What is printed?
struct N {
    int v;
    N(int x) : v(x) { std::cout << "N" << v << " "; }
    ~N() { std::cout << "~N" << v << " "; }
};
int main() {
    N arr[3] = {1, 2, 3};
}
  1. A. Compilation error: N has no default constructor
  2. B. N1 N2 N3 ~N1 ~N2 ~N3
  3. C. N1 N2 N3 ~N3 ~N2 ~N1
  4. D. N3 N2 N1 ~N3 ~N2 ~N1

Correct answer: C. N1 N2 N3 ~N3 ~N2 ~N1

Each int in the braced list implicitly converts to an N (the constructor isn't explicit), constructing arr[0..2] in index order: N1 N2 N3. When arr goes out of scope, array elements are destroyed in reverse index order: ~N3 ~N2 ~N1.

More OOP with C++ and Java questions

Exams that ask this topic