Please disable adblock to view this page.

# Complex Number operations using operator overloading & friend function (C++)

April 23, 2016

Categorised in: ,

```/* Design a C++ class complex with data members for real and imaginery
parts provide default and parameterized constructors. Write a program to
perform arithmetic operations of two complex numbers using operator overloading.
Use either member function or friend function.
*/

/*
Theory:
Operator overloading through member function: Binary -> 1 formal parameter,
Unary -> 0 formal parameter

Operator overloading through friend function: Binary -> 2 formal parameter,
Unary -> 1 formal parameter
*/

#include<iostream>

using namespace std;

class complex {

double real;
double imaginery;

public:

static int num;

complex(){
real = 0; imaginery = 0;
}

complex(double a1, double a2){
real = a1;
imaginery = a2;
}

complex operator +(complex c){
complex temp;
temp.real = this->real + c.real;
temp.imaginery = this->imaginery + c.imaginery;
return(temp);
}

complex operator *(complex c){
complex temp;
temp.real = (this->real * c.real) – (this->imaginery * c.imaginery);
temp.imaginery = (this->imaginery * c.real) + (this->real * c.imaginery);
return(temp);
}

complex operator /(complex c){
complex temp;
//OR we can take common div: int div = (c.real*c.real) + (c.imaginery*c.imaginery);
temp.real=((real*c.real)+(imaginery*c.imaginery))/((c.real*c.real)+(c.imaginery*c.imaginery));
temp.imaginery=((imaginery*c.real)-(real*c.imaginery))/((c.real*c.real)+(c.imaginery*c.imaginery));
return(temp);
}

friend complex operator -(complex c1, complex c2){
complex temp;
temp.real = c1.real – c2.real;
temp.imaginery = c1.imaginery – c2.imaginery;
return(temp);

}

void display(int flag){

if(flag == 1) cout<<"Addition:"<<endl;
else if(flag == 2) cout<<"Subtraction:"<<endl;
else if(flag == 3) cout<<"Multiplication:"<<endl;
else if(flag == 4) cout<<"Division:"<<endl;
else{
cout<<"Operand "<<num<<":"<<endl;
}
cout<<this->real<<"+i"<<this->imaginery<<endl;

}

};

int complex::num;

int main(){

complex::num = 1;

complex obj1(3, 2);

obj1.display(0);

complex::num++;

complex obj2(6, 4);

obj2.display(0);

complex obj3;

obj3 = obj1 + obj2;

obj3.display(1);

obj3 = obj2 – obj1;        //obj2(obj1) i.e. obj2 is invoking object

obj3.display(2);

obj3 = obj1 * obj2;

obj3.display(3);

obj3 = obj2/obj1;

obj3.display(4);

return 0;

}```