C/C++ Arena

Operator overloading in C++

Make your types work with +, ==, <<, [] and more, with the conventions that keep overloaded operators unsurprising.

You can define what operators mean for your own types, so a Vec2 can be added with + and printed with <<.

Guidelines:

Example

#include <iostream>

struct Vec2 {
    int x, y;
    Vec2 &operator+=(const Vec2 &o) { x += o.x; y += o.y; return *this; }
    bool operator==(const Vec2 &) const = default;
};
Vec2 operator+(Vec2 a, const Vec2 &b) { return a += b; }
std::ostream &operator<<(std::ostream &os, const Vec2 &v) { return os << "(" << v.x << ", " << v.y << ")"; }

int main() {
    Vec2 a{1, 2}, b{3, 4};
    std::cout << a + b << " " << (a == Vec2{1, 2}) << "\n";
    return 0;
}

Output:

(4, 6) 1

Practice it