Sobes.tech
Middle

How to overload postfix and prefix increment in C++?

sobes.tech AI

Answer from AI

// Overloading prefix increment
MyClass& operator++() {
    // Increase the object's state
    value++;
    // Return a reference to the modified object
    return *this;
}
// Overloading postfix increment
MyClass operator++(int) {
    // Create a temporary copy of the object before incrementing
    MyClass temp = *this;
    // Increase the object's state
    value++;
    // Return the temporary copy (value before increment)
    return temp;
}

The difference in signatures: the postfix version has a dummy parameter int to distinguish it from the prefix.

The postfix version returns a copy of the object before modification, while the prefix returns a reference to the modified object.

Example usage:

MyClass obj(5);

// Prefix increment: first increment, then use the value
MyClass result_prefix = ++obj; // obj becomes 6, result_prefix = 6

// Postfix increment: first use the value, then increment
MyClass result_postfix = obj++; // result_postfix = 6, obj becomes 7