Operator Overloading & Rule of Five in C++
From the C++ cheat sheet · Classes & Objects · verified Jul 2026
Operator Overloading & Rule of Five
Custom operators and copy/move control.
cpp
// Quick Reference
struct Vec2 {
double x, y;
Vec2 operator+(const Vec2& o) const { return {x+o.x, y+o.y}; }
};
std::ostream& operator<<(std::ostream& os, const Vec2& v);💡 Overload operators to make your types behave like built-ins (a + b, std::cout << v).
⚡ = default (C++20) auto-generates ==, and <=> gives you all comparisons at once.
📌 Rule of Five: defining a destructor/copy/move means you likely need all five (or = default).
🟢 Best case is the Rule of Zero - use RAII members so the compiler writes all five for you.
operator-overloadingrule-of-five