Binary Operator Overloading in C++

  • Binary operator works with two operands.
  • The first operand becomes the operator overloaded function caller and the second is passed as an argument.

Example : Program demonstrating Binary operator overloading

//Arithmetic operation using Binary Operator Overloading

#include<iostream>
using namespace std;
class BinaryArithmetic
{
     private:
         float num;
     public:
         void getnumber()
         {
             num = 10;
         }
         BinaryArithmetic operator+(BinaryArithmetic &ab)
         {
             BinaryArithmetic x;
             x.num = num + ab.num;
             return x;
         }
         BinaryArithmetic operator-(BinaryArithmetic &ab)
         {
             BinaryArithmetic x;
             x.num = num - ab.num;
             return x;
         }
         BinaryArithmetic operator*(BinaryArithmetic &ab)
         {
             BinaryArithmetic x;
             x.num = num * ab.num;
             return x;
         }
         BinaryArithmetic operator/(BinaryArithmetic &ab)
         {
             BinaryArithmetic x;
             x.num = num/ab.num;
             return x;
         }
         void show()
         {
             cout<<num;
         }
};
int main()
{
     BinaryArithmetic ba1,ba2,ba3;
     ba1.getnumber();
     ba2.getnumber();
     ba3 = ba1 + ba2;
     cout<<"Addition : ";
     ba3.show();
     ba3 = ba1 - ba2;
     cout<<"\n\n Subtraction : ";
     ba3.show();
     ba3 = ba1 * ba2;
     cout<<"\n\n Multiplication : ";
     ba3.show();
     ba3 = ba1/ba2;
     cout<<"\n\n Division : ";
     ba3.show();
     return 0;
}


Output:
Addition : 20
Subtraction : 0
Multiplication : 100
Division : 1

In the above example, overloading function for addition should be declared as, BinaryArithmetic operator+(BinaryArithmetic &ab); where BinaryArithmetic is a class name and ab is an object. To call function operator() the statement is as follows:

BinaryArithmetic operator+(BinaryArithmetic &ab)
{
     BinaryArithmetic x;
     x.num = num+ab.num;
     return x;
}

Member function can be called by using class of that object. The called member function is always preceded by the object.

In the above statement, the object x invokes the operator() function and the object ab is used as an argument for the function. The data member num is passed directly. While overloading binary operators, the left-hand operand calls the operator function and the right-hand operator is used as an argument.

Binary operator requires one argument and the argument contains value of the object to the right of the operator.