Skip to content
UPEEC

Operator Overloading

Give operators like +, == and << meaning for your own types.

Intermediate
Comments 0
struct Complex {
    double re, im;
    Complex operator+(const Complex &o) const { return {re + o.re, im + o.im}; }
    bool operator==(const Complex &o) const = default;   // C++20
};

std::ostream &operator<<(std::ostream &os, const Complex &c) {
    return os << c.re << " + " << c.im << "j";
}

Overload operators only when the meaning is obvious (maths types, comparisons, streaming). Don't make + do something surprising.

Spotted a mistake or want to add detail? Suggest an improvement — Content Contributors' edits are reviewed by editors before they go live.

Discussion (0)

Sign in or join free to ask questions and discuss this topic.