Increment (++) and Decrement (–) Operator Overloading in C++
Operator overloading is a feature in object-oriented programming which allows a programmer to redefine a built-in operator to work with user-defined data types.
Why Operator Overloading?
Let’s say we have defined a class Integer for handling operations on integers. We can have functions add(), subtract(), multiply() and divide() for handling the respective operations. However, to make the code more intuitive and enhance readability, it is preferred to use operators that correspond to the given operations(+, -, *, / respectively) i.e. we can replace the following code.
Replace i5 = divide(add(i1, i2), subtract(i3, i4)) by a simpler code: i5 = (i1 + i2) / (i3 - i4)
Overloading the Increment Operator
The operator symbol for both prefix(++i) and postfix(i++) are the same. Hence, we need two different function definitions to distinguish between them. This is achieved by passing a dummy int parameter in the postfix version.
Here is the code to demonstrate the same.
Example: Pre-increment overloading
Before increment: i = 3 After pre increment: i = 4
Example: Post-Increment Overloading
Before increment: i = 3 After post increment: i = 3
Overloading the Decrement Operator
Similarly, we can also overload the decrement operator as follows:
Example: Pre-Decrement Overloading
Before decrement: i = 3 After pre decrement: i = 2
Example: Post-Decrement Overloading
Before decrement: i = 3 After post decrement: i = 3