Operator Overloading is a technique of polymorphism by which an operator(+,- etc) can be used to do different types of operations.
eg:+ can be used to add two integers say a and b using sum=a+b similarly two floating point numbers say fa,fb by fs=fa+fb.
In this example +,-,*,- operators are overloaded to add,subtract, multiply and divide two complex numbers.
First a class named complex is created which has overloaded operators like + specified by a function 'complex operator +(complex c2)' which can used to add two complex numbers like c3=c1+c2 where c1,c2 and c3 are complex numbers.The complete source in C++ to implement operator overloading is provided below

```
#include<iostream.h>
#include<conio.h>
class complex
{
int a,b;
public:
void read()
{
cout<<"\n\nEnter the REAL PART : ";
cin>>a;
cout<<"\n\nEnter the IMAGINARY PART : ";
cin>>b;
}
complex operator +(complex c2)
{
complex c3;
c3.a=a+c2.a;
c3.b=b+c2.b;
return c3;
}
complex operator -(complex c2)
{
complex c3;
c3.a=a-c2.a;
c3.b=b-c2.b;
return c3;
}
complex operator *(complex c2)
{
complex c3;
c3.a=(a*c2.a)-(b*c2.b);
c3.b=(b*c2.a)+(a*c2.b);
return c3;
}
complex operator /(complex c2)
{
complex c3;
c3.a=((a*c2.a)+(b*c2.b))/((c2.a*c2.a)+(c2.b*c2.b));
c3.b=((b*c2.a)-(a*c2.b))/((c2.a*c2.a)+(c2.b*c2.b));
return c3;
}
void display()
{
cout<<a<<"+"<<b<<"i";
}
};
void main()
{
complex c1,c2,c3;
int choice,cont;
do
{
clrscr();
cout<<"\t\tCOMPLEX NUMBERS\n\n1.ADDITION\n\n2.SUBTRACTION\n\n3.MULTIPLICATION\n\n4.DIVISION";
cout<<"\n\nEnter your choice : ";
cin>>choice;
if(choice==1||choice==2||choice==3||choice==4)
{
cout<<"\n\nEnter the First Complex Number";
c1.read();
cout<<"\n\nEnter the Second Complex Number";
c2.read();
}
switch(choice)
{
case 1 : c3=c1+c2;
cout<<"\n\nSUM = ";
c3.display();
break;
case 2 : c3=c1-c2;
cout<<"\n\nResult = ";
c3.display();
break;
case 3 : c3=c1*c2;
cout<<"\n\nPRODUCT = ";
c3.display();
break;
case 4 : c3=c1/c2;
cout<<"\n\nQOUTIENT = ";
c3.display();
break;
default : cout<<"\n\nUndefined Choice";
}
cout<<"\n\nDo You Want to Continue?(1-Y,0-N)";
cin>>cont;
}while(cont==1);
getch();
}
```

Nice

ReplyDelete