ProgrammingHardMicrosoft/Amazon SDE MCQ · GATE CS

What is printed?

What is printed?
struct C {
    static int n;
    C()         { ++n; }
    C(const C&) { ++n; }
    ~C()        { --n; }
};
int C::n = 0;
void f(C c) { cout << C::n; }
int main() {
    C a;
    f(a);
    cout << C::n;
    { C b[3]; cout << C::n; }
    cout << C::n;
}
  1. A. 2141
  2. B. 1141
  3. C. 2131
  4. D. 2241

Correct answer: A. 2141

Inside f the copied parameter makes n = 2; after the call it is destroyed (n = 1). The array adds 3 (n = 4) and its destruction at the brace takes n back to 1.

More OOP with C++ and Java questions

Exams that ask this topic