Write a C++ program to overload '+' operator using member function to add two complex numbers.


Q.) Write a C++ program to overload '+' operator using member function to add two complex numbers.

Subject: object oriented programming
#include 
#include 

using namespace std;

class Complex {
private:
    double real;
    double imag;

public:
    Complex() {
        real = 0.0;
        imag = 0.0;
    }

    Complex(double r, double i) {
        real = r;
        imag = i;
    }

    Complex operator+(const Complex& other) {
        Complex result;
        result.real = real + other.real;
        result.imag = imag + other.imag;
        return result;
    }

    void print() {
        cout << "(" << real << ", " << imag << "i" << ")" << endl;
    }
};

int main() {
    Complex c1(3.0, 4.0);
    Complex c2(5.0, -2.0);

    Complex c3 = c1 + c2;

    cout << "c1 = ";
    c1.print();

    cout << "c2 = ";
    c2.print();

    cout << "c3 = c1 + c2 = ";
    c3.print();

    return 0;
}

Explanation:

  1. We define a Complex class to represent complex numbers. It has two private data members, real and imag, to store the real and imaginary parts of the complex number, respectively.

  2. We define a constructor that takes two double parameters, r and i, and initializes the real and imag data members with these values.

  3. We define an overloaded + operator using the member function syntax. This operator takes a const Complex& parameter other and returns a Complex object. Inside the operator function, we calculate the sum of the real and imaginary parts of the two complex numbers and store the result in a new Complex object, which we return as the result.

  4. We define a print() member function in the Complex class to print the complex number in the format (real, imag i).

  5. In the main() function, we create two Complex objects, c1 and c2, with the values (3.0, 4.0) and (5.0, -2.0), respectively.

  6. We create a third Complex object, c3, by adding c1 and c2 using the overloaded + operator.

  7. We print the values of c1, c2, and c3 using the print() member function.

When we run this program, it will output the following:

c1 = (3, 4i)
c2 = (5, -2i)
c3 = c1 + c2 = (8, 2i)

This shows that the + operator has been successfully overloaded to add two complex numbers.