In this article, you’ll learn to make C++ Program to Subtract Complex Number Using Operator Overloading.
Complex numbers are mathematical entities consisting of a real part and an imaginary part, denoted by the symbol “i”. They are commonly used in various scientific and engineering fields. In C++, we can create a custom class to represent complex numbers and define operator overloading to enable arithmetic operations like subtraction using the familiar minus (-) symbol.
Binary Operator Overloading to Subtract Complex Number
#include <iostream>
using namespace std;
class Complex
{
private:
float real;
float imag;
public:
Complex(): real(0), imag(0){ }
void input()
{
cout << "Enter real and imaginary parts respectively: ";
cin >> real;
cin >> imag;
}
// Operator overloading
Complex operator - (Complex c2)
{
Complex temp;
temp.real = real - c2.real;
temp.imag = imag - c2.imag;
return temp;
}
void output()
{
if(imag < 0)
cout << "Output Complex number: "<< real << imag << "i";
else
cout << "Output Complex number: " << real << "+" << imag << "i";
}
};
int main()
{
Complex c1, c2, result;
cout<<"Enter first complex number:\n";
c1.input();
cout<<"Enter second complex number:\n";
c2.input();
// In case of operator overloading of binary operators in C++ programming,
// the object on right hand side of operator is always assumed as argument by compiler.
result = c1 - c2;
result.output();
return 0;
}
Output
Enter first complex number:
Enter real and imaginary parts respectively: 2 4
Enter second complex number:
Enter real and imaginary parts respectively: 4 5
Output Complex number: -2-1i
In this program, three objects of type Complex are created and user is asked to enter the real and imaginary parts for two complex numbers which are stored in objects c1
and c2
.
Then statement result = c1 -c 2
is executed. This statement invokes the operator function Complex operator - (Complex c2)
.
When result = c1 - c2
is executed, c2
is passed as argument to the operator function.
In case of operator overloading of binary operators in C++ programming, the object on right hand side of operator is always assumed as argument by compiler.
Then, this function returns the resultant complex number (object) to main() function which is displayed as output on to the screen.