Operator Overloading (C++)

Operator overloading lets you define how built-in operators like +, ==, or << behave for your own types. This makes custom classes feel as natural to use as built-in types.

C++

You overload an operator by defining a function named operator followed by the symbol, such as operator+. For example, you can make two Point objects add together with a simple + sign.

Overloading << is what lets you print your own types with std::cout. Used carefully it improves readability, but overloading operators in surprising ways can make code confusing.

Syntax

ReturnType operator+(const T& other) const { ... }

Examples

C++

#include <iostream>

struct Point {
    int x, y;
    Point operator+(const Point& o) const {
        return {x + o.x, y + o.y};
    }
};

int main() {
    Point a{1, 2}, b{3, 4};
    Point c = a + b;
    std::cout << c.x << "," << c.y << std::endl;
    return 0;
}

Output:

4,6

Learn it in a lesson

See also

Back to the Dictionary