Overloading Pre Increment Operator(++)

Written by Raza on. Posted in C++

C supports a number of arithmetic and logical operators. Post and Pre Increment operators are one of these arithmetic operators. These incremental operators add up one to existing value of the variable.The difference between post increment and pre increment is obvious from their name: post increment is placed after the variable and pre increment is placed before the variable. In principle, there is a slight difference in their behavior which I shall explain to you in this article.


Pre Increment VS Post Increment

We have a hypothetical variable ‘num’ with us. We post increment it like this.

num ;

and pre increment it like this.

num ;

This way, there is no difference between these two operators. But in certain cases, there comes a significant difference between them. Look here.

<p>.  intnum = 5 ;</p>
<p>.  int a = num ;</p>
<p>.  int  b = num ;</p>


Now follow me. In the first case, we are doing post increment on ‘num’and storing it in ‘a’.What happens is that first the value of ‘num’ is stored in ‘a’ and then ‘num’increases by one. After the second line is executed, ‘a’ becomes equal to 5 and ‘num’ is now equal to 6.

In the third line, ‘num’ is pre incremented and its value is stored in another variable ‘b’. In this case, first ‘num’ increases by one, and then its value gets stored in ‘b’. So after execution of the third line, both ‘num’ and ‘b’ are equal to 7.


Function of Pre Increment:

Now that we have a clear concept of post and preincrement operators and their difference, we can write the overloaded function for pre increment operator. The process is casino online pretty simple. Inside the function, we increment the value of our variable by one and then return that objectby reference. In this case, we are working yet again with our Fraction class. Here is the source code for Pre Increment Operator in our Fraction Class as a member function.

<p>Fraction&amp; operator ()<br />
{<br />
.   num = num den ;<br />
.   return (*this) ;<br />

Make sure to return the object by reference and not by value.If you return it by value, then you would be unable to following operation in your program if you like it.

<p>.  Fraction f1 (3, 2) ;</p>
<p>.  Fraction f2 (1, 0) ;</p>
<p>.  cout&lt;&lt; f1 &lt;&lt;endl ;</p>
<p>.   f1 = f2 ;</p>
<p>.  cout&lt;&lt; f1 &lt;&lt;endl ;</p>

When you first output the value of f1, it is 3/2. Then you increment its value to become 5/2 and immediately afterwards store the value of f2 in it. The second time you output f1, value one should get printed but oops! 5/2 is printed and not 1. This is because you had not returned the object by reference from the pre increment function. So no change was made in f1 when you made it equal to f2. Next time I would explain how to overload the post increment operator in this very class.

Tags: , , , ,