-->

overloaded of binary operator

1 minute read

 Explain overloading of binary operator?

Ø A binary operator can be overloaded.
Ø Following program shows how the binary +(plus) operator is overloaded.
Ø Example:


#include <iostream.h>

class complex
{
float x;              //real part
float y;              //imaginary part
public:
                 complex() {  }
                 complex(float real, float imag)
{ x = real;   y = imag;  }

complex operator+(complex c)
{
         complex temp;           // templarory
         temp.x = x + c.x;
         temp.y = y + c.y;
         return (temp);
}
void display()
{
         cout << x << “ + j” << y << “\n”;
}
};
int main()
{
         complex C1,C2,C3;            //invokes constructor 1
         C1 = complex(2.5,3.5);               //invokes constructor 2
         C2 = complex(1.6,2.7);
         C3 = C1 + C2;  

         cout << “C1 : “; C1.display();
         cout << “C2 : “; C2.display();
         cout << “C3 : “; C3.display();

         return0;
}
Ø  The output of the program would be:

C1 = 2.5 + j3.5
C2 = 1.6 + j2.7
C3 = 4.1 + j6.2

Ø We used the operator function as the member function so it receives only one complex type argument explicitly.
Ø Member function is invoked only by an object of the same class. Here, the object C1 takes the responsibility of invoking the function and C2 plays the role of an argument.
Ø The invocation statement is equivalent to
Ø C3 = C1.operator+ (c2);
Ø In overloading of binary operators, the left-hand operand is used to invoke the operator function and the right-hand operand is passed as an argument.