ProgrammingVery hardProduct-company placement · 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);
    { C b[3]; cout << C::n; }
    cout << C::n;
}
  1. A. 141
  2. B. 242
  3. C. 241
  4. D. 251

Correct answer: C. 241

Passing by value copy-constructs the parameter, so f prints 2; the parameter is destroyed before the next statement (n = 1). The array adds 3 (prints 4) and its elements are destroyed at the closing brace, leaving 1. 141 forgets the copy constructor.

More OOP with C++ and Java questions

Exams that ask this topic