ProgrammingVery hardProduct company interview · GATE level

What is printed?

What is printed?
struct N {
    int v = 0;
    N& operator++()   { cout << "pre "; ++v; return *this; }
    N  operator++(int) { cout << "post "; N t = *this; ++v; return t; }
};
int main() {
    N n;
    ++n;
    n++;
    N m = n++;
    ++(++n);
    cout << n.v << " " << m.v;
}
  1. A. pre post post pre pre 5 3
  2. B. pre post post pre pre 5 2
  3. C. pre post post pre 4 2
  4. D. pre post post pre pre 4 2

Correct answer: B. pre post post pre pre 5 2

++n calls the prefix operator (v = 1); n++ calls the postfix operator, the one with the dummy int parameter (v = 2). N m = n++ copies the old value into m (m.v = 2) and increments n to 3. ++(++n) works because prefix ++ returns a reference to n itself, so both increments apply to n: v = 5. If prefix returned by value, the outer ++ would increment a temporary copy and n.v would be 4.

More OOP with C++ and Java questions

Exams that ask this topic