Today's lesson is about overloading increment and decrement operators. This might not seem like much, but in fact, these operators are going to be really interesting to overload. Just to remind ourselves, increment (++) and decrement (--) operators have what we call "side effects": informally, a side effect is a result of an operator, expression, statement, or function that persists even after the operator, expression, statement, or function has finished being evaluated. We also know that increment and decrement operators have two forms: prefix and postfix. This fact is important in a sense that we will now have different ways of overloading these forms.
The prefix form of the increment/decrement operators is slightly easier to overload, so we'll start with that. (We will explain everything using the example of the increment operator, since overloading the decrement operator is completely analogous).
The increment operator is overloaded as a method - this is the first thing to remember.
Let's see the code:
Complex operator++()
{
++re; ++im;
return *this;
}
The above method is pretty simple and self-explanatory. It simply performs the increment, and returns the same object. The postfix version is a little bit more tricky. It is also overloaded as a method, but it has to have a single, "dummy"
int
parameter, for disambiguation purposes.
Complex operator++(int k)
{
Complex w(re, im);
re++; im++;
return w;
}
As we can see, in the postfix version, first we make a copy of our object, which we later return. This is due to the definition of this operator: first the value is returned, then the increment happens (the increment being a side effect in this case). From the two implementations above, we can also notice possible differences in performance, as the postfix version performs an expensive copy operation.
Overloading increment and decrement operators is simple, but still very important, as they're among the most used ones. In the next few articles we are going to talk about overloading some other groups of operators, so make sure you stay tuned!
Online example: http://cpp.sh/6stp