Operator overloading

Applies to: cpp

Operator overloading lets your own types use built-in operators (+, ==, <<) by defining functions like operator+. It makes math types (vectors, matrices) read naturally, but use it only where the meaning is obvious.

struct Vec2 { double x, y; };
Vec2 operator+(Vec2 a, Vec2 b) { return {a.x+b.x, a.y+b.y}; }
Vec2 c = a + b;             // reads like math

See also: struct-vs-class, template