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:
- Only overload an operator when its meaning is obvious (math types, containers, comparisons).
- Implement
+=as a member and+in terms of it. operator<<for printing takesstd::ostream &and returns it, so calls can chain.- In C++20,
bool operator==(const T &) const = default;andauto operator<=>(const T &) const = default;generate comparisons for you.
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