C++ operator overloading

Operator overloading lets a user-defined type work with the usual operators. A 2D vector class can define + and - for vectors, * for scaling, == for comparison, and << for printing. Done well, code such as a + b * 2 reads like the mathematics.

C++
#include <iostream>

struct Vec2 {
  int x;
  int y;

  Vec2 operator+(const Vec2& other) const { return {x + other.x, y + other.y}; }
  Vec2 operator-(const Vec2& other) const { return {x - other.x, y - other.y}; }
  Vec2 operator*(int k) const { return {x * k, y * k}; }
  bool operator==(const Vec2& other) const { return x == other.x && y == other.y; }
};

std::ostream& operator<<(std::ostream& out, const Vec2& v) {
  return out << "(" << v.x << ", " << v.y << ")";
}

int main() {
  Vec2 a{1, 2};
  Vec2 b{3, 4};
  std::cout << a + b << "\n";
  std::cout << b - a << "\n";
  std::cout << a * 3 << "\n";
  std::cout << (a + b == Vec2{4, 6}) << " " << (a == b) << "\n";
}
Read the full lesson