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.

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++.

Leave a Reply

five × one =