Problem: Write a C++ program to add and subtract two complex numbers by overloading the + and – operators.
We often overload an operator in C++ to operate on user-defined objects.
If we define complex numbers as objects, we can easily use arithmetic operators such as additional (+) and subtraction (-) on complex numbers with operator overloading.
In the following C++ program, I have overloaded the + and – operator to use it with the Complex
class objects.
#include <iostream>
using namespace std;
class Complex{
public:
float real;
float img;
Complex(){
this->real = 0.0;
this->img = 0.0;
}
Complex(float real, float img){
this->real = real;
this->img = img;
}
//overloading + operator
Complex operator+(const Complex &obj){
Complex temp;
temp.img = this->img + obj.img;
temp.real = this->real + obj.real;
return temp;
}
//overloading - operator
Complex operator-(const Complex &obj){
Complex temp;
temp.img = this->img - obj.img;
temp.real = this->real - obj.real;
return temp;
}
void display(){
cout << this->real << " + " << this->img << "i" << endl;
}
};
int main()
{
Complex a, b, c;
cout << "Enter real and complex coefficient of the first complex number: " << endl;
cin >> a.real;
cin >> a.img;
cout << "Enter real and complex coefficient of the second complex number: " << endl;
cin >> b.real;
cin >> b.img;
cout << "Addition Result: ";
c = a+b;
c.display();
cout << "Subtraction Result: ";
c = a-b;
c.display();
return 0;
}
Output:
Enter real and complex coefficient of the first complex number:5 6
Enter real and complex coefficient of the second complex number:
1 2
Addition Result: 6 + 8i
Subtraction Result: 4 + 4i
Explanation:
In the above program, we have created Complex
class with two attributes:
real
: To store the real coefficient value.img
: To store the imaginary coefficient value.
Inside the class declaration, we have overloaded the + operator by adding the real and imaginary values of the current instance (i.e this
) and the passed instance (i.e. obj
), inside the operator+
method.
We store the result into a new complex object (i.e. temp
) and return the same.
We do the same to overload the – operator, but instead of adding we subtract the corresponding coefficient.
In this programming example, we learned to add and subtract complex numbers using the concept of operator overloading in C++.