
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Subtract Complex Number Using Operator Overloading in C++
Operator overloading can be done with most of the built-in operators in C++. The overloaded operators are functions with the keyword operator followed by the operator symbol that is defined. The overloaded operators have a return type and a parameter list like any function.
A program that subtracts complex numbers using operator overloading is as follows −
Example
#include<iostream> using namespace std; class ComplexNum { private: int real, imag; public: ComplexNum(int r = 0, int i =0) { real = r; imag = i; } ComplexNum operator - (ComplexNum const &obj1) { ComplexNum obj2; obj2.real = real - obj1.real; obj2.imag = imag - obj1.imag; return obj2; } void print() { if(imag>=0) cout << real << " + i" << imag <<endl; else cout << real << " + i(" << imag <<")"<<endl; } }; int main() { ComplexNum comp1(15, -2), comp2(5, 10); cout<<"The two comple numbers are:"<<endl; comp1.print(); comp2.print(); cout<<"The result of the subtraction is: "; ComplexNum comp3 = comp1 - comp2; comp3.print(); }
Output
The two comple numbers are: 15 + i(-2) 5 + i10 The result of the subtraction is: 10 + i(-12)
In the above program, the class ComplexNum is defined which has variables real and imag for the real and imaginary part of a complex number respectively. The constructor ComplexNum is used to initialize the values of real and imag. It also contains the default values as 0. This is shown in the following code snippet −
class ComplexNum { private: int real, imag; public: ComplexNum(int r = 0, int i =0) { real = r; imag = i; } }
The function that is the overloaded operator contains the keyword operator followed by - as that is the operator being overloaded. The function subtracts the two complex numbers and the result is stored in the object obj2. Then this value is returned to the ComplexNum object comp3.
The following code snippet demonstrates this −
ComplexNum operator - (ComplexNum const &obj1) { ComplexNum obj2; obj2.real = real - obj1.real; obj2.imag = imag - obj1.imag; return obj2; }
The print() function prints the real and imaginary part of the complex number. This is shown as follows.
void print() { if(imag>=0) cout << real << " + i" << imag <<endl; else cout << real << " + i(" << imag <<")"<<endl; }