Skip to main content

Compare complex magnitude by overloading

Short answer

Overload <, >, and == to compare magnitudes sqrt(re²+im²); == uses a small tolerance. For c1=3+4i (mag 5) and c2=5+12i (mag 13), c2 has greater magnitude.

Write a program to compare the magnitude of complex numbers by overloading <, > and == operators.

The magnitude (modulus) of a complex number z = a + bi is |z| = √(a² + b²). The operators <, > and == are overloaded as member functions that compare these magnitudes and return bool. For ==, floating-point values are compared with a small tolerance.

#include <iostream>
#include <cmath>
using namespace std;

class Complex {
    float re, im;
public:
    void read() {
        cout << "Enter real and imaginary part: ";
        cin >> re >> im;
    }
    float magnitude() const { return sqrt(re * re + im * im); }

    bool operator<(const Complex &c) const {
        return magnitude() < c.magnitude();
    }
    bool operator>(const Complex &c) const {
        return magnitude() > c.magnitude();
    }
    bool operator==(const Complex &c) const {
        return fabs(magnitude() - c.magnitude()) < 1e-6;
    }
};

int main() {
    Complex c1, c2;
    c1.read();
    c2.read();
    cout << "|c1| = " << c1.magnitude()
         << ", |c2| = " << c2.magnitude() << endl;

    if (c1 > c2)       cout << "c1 has the greater magnitude" << endl;
    else if (c1 < c2)  cout << "c2 has the greater magnitude" << endl;
    else if (c1 == c2) cout << "Both have equal magnitude" << endl;
    return 0;
}

Sample run:

Enter real and imaginary part: 3 4
Enter real and imaginary part: 5 12
|c1| = 5, |c2| = 13
c2 has the greater magnitude

For 3 4 and 4 3 the program prints "Both have equal magnitude", because both have |z| = 5, even though the numbers are different.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Object Oriented Programming chapter 5 questions →