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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 | #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++.