ProgrammingVery hardProduct company interview · GATE level

What is printed?

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

Correct answer: A. -2

Only the default constructor increments n. The by-value parameter of f and the local b are made by the implicitly generated copy constructor, which does not touch n, but each of them is later destroyed and its destructor decrements n. a: n = 1; two calls of f: n = -1; the block with b: n = -2 (a itself is destroyed only after the print). The fix is a user-written copy constructor that also increments n.

More OOP with C++ and Java questions

Exams that ask this topic