Overloading Plus Equal operator (+=)

Written by Raza on. Posted in C++

There are various types of operators in C++. In our recent posts, we have covered overloading of a bunch of arithmetic operators. There are some arithmetic operators which perform compound functions. It means they handle more than one mathematical function at a time. The Plus Equal or Addition Assignment Operator or plus equals to operator (+=) is one of these. As the name implies, it adds and assigns the value to the variable at the same time. The plus equal operator is quite often used in programming. We shall learn how to overload it. 


Function of Addition Assignment Operator:

Addition assignment operator is used in this way for a certain variable.

<p>int num = 5 ;</p>
<p>num += 10 ;</p>
<p>cout &lt;&lt; num ;</p>


The output of num would be 15 here. This plus equal operation is equivalent to this statemtent.

<p>num = num + 10 ;</p>

In short, the addition assignment operator is a shortcut for adding the value of a variable in itself and then adding the other value as well. Using this operator saves us much of syntax and extra code.

From the usage of the plus equal operator, it becomes quite simple how to write its overloaded function. The function would take and object as a parameter, add the value of the object itself and the passed object and return the object upon which the function was called. What more, it is the mixture of addition operator and assignment operators. If you have overloaded them successfully in your program, overloading plus equals operator is just a piece of cake.


Source Code for Plus Equal Operator:

We work again with our Fraction Class this time. Here is a basic source code for the addition assignment or plus and equal to operator as whatever you may call it.

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


Again remember to return by reference from the function. The minus equal, multiply equal and all such other operators would be overloaded in a similar way as the plus equal operator has been overloaded.

Tags: , , , ,