The postfix ++ operator (x++) says to increment (increase) a value by 1 after the current value has been used in the rest of the expression. This produces a challenge for implementing the postfix ++ operator. We need to return the original value before it was incremented, while still incrementing the value.
To make this happen, we need to do some slight of hand. First, we will copy the current value of x into a temporary variable. Then we will increment x. We then return the temporary variable, which holds the original value of x before it was incremented. Because we are going to return a new object (the copy), the return value will not be a reference.
We also need a way to indicate whether operator++() refers to the prefix or postfix operator. The convention used is to specify an anonymous int parameter to indicate βthis is the postfix versionβ. So the final prototype for the post-increment operator looks like:
In this version, as r2 = r1++ runs, the r1++ executes first. It changes r1, but then returns a copy of the temp variable, which holds the original value of r1 before the increment. So r2 = r1++ becomes r2 = (temp); and r2 sees the right value to copy.
Because the postfix version needs to make a copy, it is potentially less efficient than the prefix version. For simple data like int, the difference is negligible. But for larger objects, like Rational, it can be a significant performance hit to make a copy of the object. A compiler may be able to optimize this difference away. But rather than rely on that, we should prefer the prefix operator if we donβt care about the way the two versions interact with the rest of an expression. (And in general, we shouldnβt care about that! Complex expressions with ++x or x++ in the middle are a great way to cause confusion.)