WAP to overload binary + and - operator using friend function
Objective
Write a C++ program to overload binary (+) and (-) operators for Complex numbers using Friend functions.
Algorithm / Approach
- Create a
class Complex1. - Declare two friend functions:
friend Complex1 operator+(Complex1, Complex1)and the same for-. - Implement the functions globally, taking two objects as arguments, performing the math on their private variables, and returning a new object.
- In
main(), add and subtract the objects using standard mathematical syntax.
main.cpp
#include<iostream>
using namespace std;
class Complex1{
int real, imag;
public:
Complex1(int r, int i) {
real = r;
imag = i;
}
Complex1() { }
void display() {
if(imag>= 0)
cout<< real<<" +i "<< imag<< endl;
else
cout<< real<<" -i "<< imag<< endl;
}
friend Complex1 operator+(Complex1 ob1, Complex1 ob2) ;
friend Complex1 operator-(Complex1 ob1, Complex1 ob2 );
};
Complex1 operator+(Complex1 ob1, Complex1 ob2) {
int a = ob1.real+ob2.real;
int b = ob1.imag+ob2.imag;
return Complex1(a,b);
}
Complex1 operator-(Complex1 ob1, Complex1 ob2 ) {
int a = ob1.real-ob2.real;
int b = ob1.imag-ob2.imag;
return Complex1(a,b);
}
int main() {
int a,b,c,d;
cout<<"Enter real & imag part of no 1: ";
cin>>a>>b;
cout<<"Enter real & imag part of no 2: ";
cin>>c>>d;
Complex1 c1(a,b),c2(c,d),c3,c4;
c3 = c1+c2;
c3.display();
c4 = c1-c2;
c4.display();
return 0;
}
Expected Output
Enter real and imag part of no 1: 10 10 Enter real and imag part of no 1: 5 15 15 +i 25 5 -i -5
Explanation of the Program
- While binary operators between two objects are usually implemented as member functions, they can also be implemented as global
friendfunctions. - When implemented as a friend function, the compiler translates
c1 + c2into a global function call:operator+(c1, c2).
Complexity
Time Complexity
O(1)
Space Complexity
O(1)