Sobes.tech
Junior — Middle

How can the behavior of the postfix increment operator be implemented?

sobes.tech AI

Answer from AI

The postfix increment operator (e.g., i++) first returns the current value of the variable, then increases it by 1. To implement such behavior, you can overload the operator in C++ or write a function that returns the value before the increment.

Example of implementation in C++ with operator overloading:

class Counter {
    int value;
public:
    Counter(int v) : value(v) {}

    // Postfix operator++
    Counter operator++(int) {
        Counter temp = *this; // save current state
        value++;             // increment value
        return temp;         // return old value
    }

    int get() const { return value; }
};

// Usage:
// Counter c(5);
// Counter old = c++; // old.value == 5, c.value == 6

In C without operator overloading, you can implement a function that returns the value before the increment:

int postIncrement(int* p) {
    int old = *p;
    (*p)++;
    return old;
}

Thus, the key point is to save the old value, increment the variable, and return the saved value.