A C++ program that demonstrates Operator Overloading for the
+
operator on a Complex
number class.#include <iostream>using namespace std;class Complex {int real, imag; // Real and imaginary partspublic:// Constructor with default valuesComplex(int r = 0, int i = 0) {real = r;imag = i;}// Overloading + operatorComplex operator + (Complex const &obj) {// Add real and imaginary parts separatelyreturn Complex(real + obj.real, imag + obj.imag);}// Function to display complex numbervoid display() {cout << real << " + " << imag << "i" << endl;}};int main() {Complex c1(2, 3), c2(4, 5);// Calls overloaded operator+Complex c3 = c1 + c2;// Display resultc3.display(); // Output: 6 + 8ireturn 0;}
Output
6 + 8i
Explanation
Complex(int r = 0, int i = 0) Constructor initializes complex real and imaginary values.
Complex operator + (Complex const &obj) → Operator + Overloads operator + to add two complex numbers.
Adds real parts separately.
One adds imaginary parts one at a time.
c1 + c2 is converted automatically in main to c1. operator + c2.
Result in c3 is added to result in c2 = (2 + 4) + (3 + 5)i = 6 + 8i.
This is a classic Operator Overloading example.
Thanks for reading 💗!
⮕ Share it with others who might benefit.
⮕ Leave a comment with your thoughts or questions—I’d love to hear from you.
⮕ Follow/Subscribe to the blog for more helpful guides, tips, and insights.
Comments
Post a Comment