Skip to content

Module 6 · Inheritance and Polymorphism — topic 5 of 5

Operator Overloading

Give your types natural syntax: +, ==, <, <<, [] and more. Learn member vs non-member operators, return conventions and C++20's spaceship operator.

Beginner 15 min read·Lesson 26 of 40 in C++ Programming

Learning objectives

  • Overload arithmetic, comparison and stream operators
  • Choose member or non-member implementations
  • Follow the conventional return types

Definition

Operator overloading defines the meaning of built-in operators for user-defined types by writing functions named operator@, which the compiler calls when the operator is applied to objects of those types.

Introduction

std::string lets you write a + b, a == b and std::cout << a because those operators are overloaded. Your own types — vectors, fractions, money — can be just as natural to use.

Why it matters

Well-chosen operators make mathematical and value types readable: p + q instead of p.add(q).

Overloading < or == lets your types work with std::sort, std::find, std::set and std::map.

Detailed explanation

Write T operator+(const T& a, const T& b) as a non-member (often a friend) so conversions apply to both operands. Implement it in terms of operator+=, which is a member returning T&.

Comparison: bool operator==(const T&, const T&), bool operator<(...). In C++20, auto operator<=>(const T&) const = default; generates all six comparisons.

Streams: std::ostream& operator<<(std::ostream& os, const T& t) must be a non-member and should return os for chaining.

operator[] must be a member; provide const and non-const versions. Assignment operator= returns T&.

Don't overload &&, || or , (they lose short-circuit/sequencing), and keep meanings intuitive.

Syntax

C++
struct Vec2 {
double x, y;
Vec2& operator+=(const Vec2& o) { x += o.x; y += o.y; return *this; }
};
Vec2 operator+(Vec2 a, const Vec2& b) { return a += b; }
bool operator==(const Vec2& a, const Vec2& b) { return a.x == b.x && a.y == b.y; }
std::ostream& operator<<(std::ostream& os, const Vec2& v) { return os << '(' << v.x << ", " << v.y << ')'; }
  • Compound assignment is a member returning *this.
  • Binary arithmetic is usually a non-member.
  • << returns the stream.

Code examples

A 2D vector type

C++
#include <iostream>
struct Vec2 {
double x, y;
Vec2& operator+=(const Vec2& o) { x += o.x; y += o.y; return *this; }
};
Vec2 operator+(Vec2 a, const Vec2& b) { return a += b; }
Vec2 operator*(const Vec2& v, double k) { return {v.x * k, v.y * k}; }
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 << ' ' << b * 2 << '\n';
return 0;
}
Output
(4, 6) (6, 8)

Comparison for sorting

C++
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
struct Player {
std::string name;
int score;
};
bool operator<(const Player& a, const Player& b) { return a.score > b.score; } // higher score first
int main() {
std::vector<Player> v{{"Ana", 40}, {"Raj", 75}, {"Zoe", 60}};
std::sort(v.begin(), v.end());
for (const auto& p : v) std::cout << p.name << ' ';
std::cout << '\n';
return 0;
}
Output
Raj Zoe Ana

More examples

A Fraction with arithmetic, comparison and output

C++
#include <iostream>
#include <numeric>
class Fraction {
public:
Fraction(long n = 0, long d = 1) : n_(n), d_(d) { normalise(); }
Fraction& operator+=(const Fraction& o) { n_ = n_ * o.d_ + o.n_ * d_; d_ *= o.d_; normalise(); return *this; }
Fraction& operator*=(const Fraction& o) { n_ *= o.n_; d_ *= o.d_; normalise(); return *this; }
friend Fraction operator+(Fraction a, const Fraction& b) { return a += b; }
friend Fraction operator*(Fraction a, const Fraction& b) { return a *= b; }
friend bool operator==(const Fraction& a, const Fraction& b) { return a.n_ == b.n_ && a.d_ == b.d_; }
friend bool operator<(const Fraction& a, const Fraction& b) { return a.n_ * b.d_ < b.n_ * a.d_; }
friend std::ostream& operator<<(std::ostream& os, const Fraction& f) { return f.d_ == 1 ? os << f.n_ : os << f.n_ << '/' << f.d_; }
private:
void normalise() {
if (d_ < 0) { n_ = -n_; d_ = -d_; }
long g = std::gcd(n_, d_);
if (g) { n_ /= g; d_ /= g; }
}
long n_, d_;
};
int main() {
Fraction a(1, 2), b(1, 3);
std::cout << a + b << ' ' << a * b << ' ' << a + 1 << '\n';
std::cout << std::boolalpha << (a + b == Fraction(5, 6)) << ' ' << (b < a) << '\n';
Fraction sum;
for (int k = 1; k <= 4; ++k) sum += Fraction(1, k * (k + 1));
std::cout << sum << '\n';
return 0;
}
Output
5/6 1/6 3/2
true true
4/5

Step-by-step explanation

  • Compound operators update and normalise the fraction.
  • Binary + and * are friends built from the compound ones; a + 1 works because 1 converts to Fraction(1).
  • == compares normalised values; < cross-multiplies (denominators are positive).
  • The telescoping sum 1/2 + 1/6 + 1/12 + 1/20 equals 4/5.

Expected output

Running “A Fraction with arithmetic, comparison and output” prints exactly:

TextOutput
5/6 1/6 3/2
true true
4/5

Practical applications

  • Math libraries (Eigen, GLM) overload operators for vectors and matrices.
  • std::chrono durations support +, - and comparisons.
  • Big-integer and money classes overload arithmetic.

Best practices

  • Implement + in terms of +=.
  • Keep operator meanings intuitive.
  • In C++20, default the spaceship operator for member-wise comparison.

Common mistakes

operator<< as a member

Avoid

struct P { std::ostream& operator<<(std::ostream& os); };

Prefer

std::ostream& operator<<(std::ostream& os, const P& p);

As a member it would be called as p << std::cout. The stream must be the left operand.

Returning by value from operator+=

Avoid

Vec2 operator+=(const Vec2& o) { x += o.x; return *this; }

Prefer

Vec2& operator+=(const Vec2& o) { x += o.x; return *this; }

Compound assignment should return a reference so (a += b) += c modifies a.

Important notes

  • C++20: auto operator<=>(const T&) const = default; plus bool operator==(const T&) const = default; generate all comparisons.
  • You cannot create new operators or change precedence and arity.

Key takeaways

  • Operators are functions named operator@.
  • Members: +=, =, []; non-members: +, ==, <<.
  • << returns the stream for chaining.

Try it yourself

  1. 1
    Add -, / and != to the Fraction class.
  2. 2
    Write a Matrix2x2 class with * and << operators.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

6 questions test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhat is printed?
  • BeginnerWhy is `operator<<` for printing usually a non-member function?
  • ModerateWhat is printed?
Practise this topic