In this example, you'll learn to overload increment ++ and decrement -- operators in C++.
In this tutorial, increment ++ and decrements -- operator are overloaded in best possible way, i.e., increase the value of a data member by 1 if ++ operator operates on an object and decrease value of data member by 1 if -- operator is used.
Initially when the object obj is declared, the value of data member i for object obj is 0 (constructor initializes i to 0).
When ++ operator is operated on obj, operator function void operator++( ) is invoked which increases the value of data member i to 1.
It is because the return type of operator function in above program is void.
Here is the little modification of above program so that you can use code obj1 = ++obj.
This program is similar to the one above.
The only difference is that, the return type of operator function is Check in this case which allows to use both codes ++obj; obj1 = ++obj;. It is because, temp returned from operator function is stored in object obj.
Since, the return type of operator function is Check, you can also assign the value of obj to another object.
Notice that, = (assignment operator) does not need to be overloaded because this operator is already overloaded in C++ library.
Overloading of increment operator up to this point is only true if it is used in prefix form.
This is the modification of above program to make this work both for prefix form and postfix form.
// Notice int inside barcket which indicates postfix increment.
// Assigns value of obj to obj1, only then operator function is called.
When increment operator is overloaded in prefix form; Check operator ++ () is called but, when increment operator is overloaded in postfix form; Check operator ++ (int) is invoked.
Notice, the int inside bracket. This int gives information to the compiler that it is the postfix version of operator.
Don't confuse this int doesn't indicate integer.
Decrement operator can be overloaded in similar way as increment operator.
// Notice int inside barcket which indicates postfix decrement.
Also, unary operators like: !, ~ etc can be overloaded in similar manner.