Skip to main content

Complex numbers relational operators

Short answer

Overload == and != to compare real and imaginary parts exactly; over load >, <, >=, <= to compare magnitudes sqrt(re²+im²). For a=3+4i (mag 5) and b=1+2i (mag ≈2.236), a > b is true.

Write a program to overload relational operators (==, !=, >, <, >=, <=) to compare complex numbers.

Complex numbers are not ordered like real numbers, so we state a rule:

  • == and != compare the real and imaginary parts.
  • >, <, >=, <= compare the magnitude √(re² + im²).
#include <iostream>
#include <cmath>
using namespace std;

class Complex {
    float re, im;
public:
    Complex(float r = 0, float i = 0) { re = r; im = i; }
    float mag() const { return sqrt(re * re + im * im); }
    void show() const { cout << re << (im < 0 ? " - " : " + ")
                             << fabs(im) << "i"; }

    bool operator==(const Complex &c) const { return re == c.re && im == c.im; }
    bool operator!=(const Complex &c) const { return !(*this == c); }
    bool operator> (const Complex &c) const { return mag() >  c.mag(); }
    bool operator< (const Complex &c) const { return mag() <  c.mag(); }
    bool operator>=(const Complex &c) const { return mag() >= c.mag(); }
    bool operator<=(const Complex &c) const { return mag() <= c.mag(); }
};

int main() {
    Complex a(3, 4), b(1, 2);
    cout << "a = "; a.show(); cout << ",  b = "; b.show(); cout << endl;
    cout << "a == b : " << (a == b) << endl;
    cout << "a != b : " << (a != b) << endl;
    cout << "a >  b : " << (a >  b) << endl;
    cout << "a <  b : " << (a <  b) << endl;
    cout << "a >= b : " << (a >= b) << endl;
    cout << "a <= b : " << (a <= b) << endl;
    return 0;
}

Output:

a = 3 + 4i,  b = 1 + 2i
a == b : 0
a != b : 1
a >  b : 1
a <  b : 0
a >= b : 1
a <= b : 0

|a| = 5 and |b| = √5 ≈ 2.236, so a is greater.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Object Oriented Programming chapter 5 questions →