CPP Program to Implement the Concept of Binary Operator Overloading

Aim:

To write a C++ program to implement the concept of Binary operator overloading.

Description:

  • The binary operators take two arguments and following are the examples of Binary operators.
  • You use binary operators very frequently like addition (+) operator, subtraction (-) operator and division (/) operator.

Following example explains how addition (+) operator can be overloaded. Similar way, you can overload subtraction (-) and division (/) operators.

Algorithm:

  1. Start the program.
  2. Declare the class.
  3. Declare the variables and its member function.
  4. Using the function getvalue () to get the two numbers.
  5. Define the function operator + () to add two complex numbers.
  6. Define the function operator – () to subtract two complex numbers.
  7. Define the display function.
  8. Declare the class objects obj1, obj2 and result.
  9. Call the function getvalue using obj1 and obj2
  10. Calculate the value for the object result by calling the function operator + and Operator – Obj2 and result.
  11. Return the values.
  12. Call the display function using obj1 and
  13. Stop the program

Program:

include<iostream>
using namespace std;
class Complex
{
private:
int real;
int imag;
public:
Complex():real(0),imag(0){}
Complex(int a,int b):real(a),imag(b){}
Complex operator +(Complex);
Complex operator - (Complex);
void disp();
};
Complex Complex::operator +(Complex d)
{
Complex temp;
temp.real=real+d.real;
temp.imag=imag+d.imag;
return temp;
}
Complex Complex::operator -(Complex d)
{
Complex temp;
temp.real=real-d.real;
temp.imag=imag-d.imag;
return temp;
}
void Complex::disp()
{
cout<<real;
if(imag>=0)
{
cout<<"+"<<imag<<"i";
}
else{
cout<<"-"<<imag<<"i";
}
cout<<endl;
}
int main()
{
int a,b,c,d;
Complex z;
cout<<"ENTER THE TWO COMPLEX NUMBERS \n";
cin>>a>>b>>c>>d;
Complex x(a,b),v(c,d);
x.disp();
v.disp();
cout<<"\nSUM OF TWO COMPLEX :";
z=x+v;
z.disp();
z=x-v;
cout<<"\nDIFFERENCE OF TWO COMPLEX :";
z.disp();
return 0;	
}

Execution:

INPUT :
ENTER THE TWO COMPLEX NUMBERS :
5 7 3 1

OUTPUT :
SUM OF THE COMPLEX: 8+8i
DIFFERENCE OF TWO COMPLEX: 2+6i

Result:

Thus, the Implement the Concept of Binary Operator Overloading was executed successfully.

Leave a Comment