Overloading Binary Operators
Overloading with a single parameter is called binary operator overloading. Similar to unary operators, binary operators can also be overloaded. Binary operators require two operands, and they are overloaded by using member functions and friend functions.
- Overloading binary operators using member functions
- Overloading binary operators using friend functions
The following programs are illustrated based on the above discussion.
10.7 Write a program to overload + binary operator.
Explanation: In the above program, binary operator + is overloaded. Using the overloading operator +, addition of member variables of two objects is performed and results are assigned to member variables of third object. In this program X, Y, and Z are objects of class num. The statement Z=X+Y invokes the operator function. In this statement, the object y is assigned to object t of operator function and member variables of X are accessed directly. The object tmp is used for holding the result of addition, and it is returned to object Z after function execution. The function show() displays the values of three objects.
10.8 Write a program to perform multiplication using an integer and object. Use friend function.
Explanation: In the above program, the equation Z=3*X contains integer and class object. We know that the left-hand operand is always used to invoke the function and the right-hand operand is passed as an argument. In such type of equations, member functions are not useful because the left-hand operand is integer and cannot invoke the function. Hence, the function operator *() is declared as friend. The friend function calls the operator *() and carries the multiplication of each member variable by three. The results are displayed in the output.