Introduction & Syntax
Operator Overloading · Study material
Operator overloading in C++ lets your own types work with the familiar operators: a + b for vectors and money, a < b for sorting students, std::cout << date for printing, grid(r, c) for matrices and ptr->name for smart pointers. It is just a function with a special name – operator+, operator<< – that the compiler calls when it sees the operator. Used well, it makes code read like mathematics; used badly, it makes code unreadable. This page covers every operator you will meet in practice, the rules (member or non-member, what to return, what cannot be overloaded) and the C++20 spaceship operator, with programs you can run. Then test yourself with 60 practice questions – 20 MCQs, 20 predict-the-output puzzles, 10 find-the-error programs and 10 complete programs – verified on a real C++ compiler.
On this page
- Syntax, rules and member vs non-member operators
- Arithmetic, compound assignment and comparisons (including <=>)
- Stream << and >>, subscript [], function call (), ++ and --
- Conversion operators, -> and *, user-defined literals
- Operators you cannot overload and canonical implementations
Syntax and rules
An overloaded operator is a function named operator@, where @ is the operator. As a member the left operand is *this; as a non-member both operands are parameters.
| Expression | Member form | Non-member form |
|---|---|---|
a + b | a.operator+(b) | operator+(a, b) |
-a | a.operator-() | operator-(a) |
a += b | a.operator+=(b) | operator+=(a, b) |
a[i], a(x), a = b, a->m | must be members | – |
The rules: at least one operand must be a user-defined type; you cannot invent new operators; precedence, associativity and the number of operands stay the same; and ::, ., .*, ?:, sizeof, typeid and alignof cannot be overloaded.
Arithmetic and compound assignment
Implement += as a member that modifies *this and returns *this by reference; then write + as a non-member that copies its left operand and uses +=. Non-member binary operators treat both operands symmetrically, so 2 * v works as well as v * 2.
#include <iostream>
struct Vec2 {
double x = 0, y = 0;
Vec2& operator+=(const Vec2& o) { x += o.x; y += o.y; return *this; } // member: modifies *this
Vec2 operator-() const { return {-x, -y}; } // unary minus
};
// Non-member binary operators, written in terms of the compound one
Vec2 operator+(Vec2 a, const Vec2& b) { a += b; return a; }
Vec2 operator*(const Vec2& v, double k) { return {v.x * k, v.y * k}; }
Vec2 operator*(double k, const Vec2& v) { return v * k; } // so 2 * v works too
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 << ')'; }
int main() {
Vec2 a{1, 2}, b{3, 4};
Vec2 c = a + b * 2; // usual precedence: * before +
std::cout << c << ' ' << -c << ' ' << 2 * a << '\n';
a += b;
std::cout << a << ' ' << (a == Vec2{4, 6}) << '\n';
return 0;
}
(7, 10) (-7, -10) (2, 4) (4, 6) 1
Comparisons and the spaceship operator (C++20)
Before C++20 a type needed six comparison functions. Now operator<=> (three-way comparison) gives < <= > >=, and operator== gives == and !=. Defaulting them compares members in declaration order; write <=> yourself for a custom order.
#include <algorithm>
#include <compare>
#include <iostream>
#include <string>
#include <vector>
struct Version {
int major, minor, patch;
// C++20: one defaulted <=> gives <, <=, >, >= ; defaulted == gives == and !=
auto operator<=>(const Version&) const = default;
bool operator==(const Version&) const = default;
};
struct Student {
std::string name;
int marks;
// Custom ordering: higher marks first, then name
std::strong_ordering operator<=>(const Student& o) const {
if (auto c = o.marks <=> marks; c != 0) return c;
return name <=> o.name;
}
bool operator==(const Student&) const = default;
};
int main() {
Version a{1, 4, 2}, b{1, 10, 0};
std::cout << (a < b) << (a == b) << (a != b) << (b >= a) << '\n';
std::vector<Student> s{{"Ravi", 78}, {"Asha", 91}, {"Meena", 78}};
std::sort(s.begin(), s.end());
for (const auto& x : s) std::cout << x.name << ' ';
std::cout << '\n';
return 0;
}
1011 Asha Meena Ravi
Stream insertion and extraction
operator<< and operator>> must be non-members, because the left operand is the stream. They take the stream by reference and return it, which makes chaining possible. Declaring them as friend inside the class lets them read private members.
#include <iostream>
#include <sstream>
class Fraction {
int n_, d_;
public:
Fraction(int n = 0, int d = 1) : n_(n), d_(d) {}
friend std::ostream& operator<<(std::ostream& os, const Fraction& f) { return os << f.n_ << '/' << f.d_; }
friend std::istream& operator>>(std::istream& is, Fraction& f) {
char slash;
if (is >> f.n_ >> slash >> f.d_ && slash != '/') is.setstate(std::ios::failbit);
return is;
}
};
int main() {
std::istringstream in("3/4 5/8");
Fraction a, b;
in >> a >> b; // chaining works because >> returns the stream
std::cout << a << " and " << b << '\n';
return 0;
}
3/4 and 5/8
Subscript and function call
operator[] and operator() must be members. Provide const and non-const versions so read-only objects can be read and writable ones written. A class with operator() is a function object (functor) – it can carry state, and the standard algorithms accept it like a function. (C++23 also allows operator[] with several arguments.)
#include <iostream>
#include <stdexcept>
#include <vector>
class Grid {
int cols_;
std::vector<int> cells_;
public:
Grid(int r, int c) : cols_(c), cells_(r * c) {}
int& operator()(int r, int c) { return cells_.at(r * cols_ + c); } // grid(r, c) = 5;
int operator()(int r, int c) const { return cells_.at(r * cols_ + c); }
int* operator[](int r) { return &cells_[r * cols_]; } // grid[r][c] (no bounds check)
};
struct Multiplier { // a function object (functor) with state
int factor;
int operator()(int x) const { return x * factor; }
};
int main() {
Grid g(2, 3);
g(0, 1) = 5;
g[1][2] = 9;
std::cout << g(0, 1) + g(1, 2) << '\n';
try { g(2, 0) = 1; } catch (const std::out_of_range&) { std::cout << "out of range\n"; }
Multiplier triple{3};
std::cout << triple(14) << '\n';
return 0;
}
14 out of range 42
Increment and decrement
The prefix form operator++() returns a reference to the updated object. The postfix form takes a dummy int parameter and returns a copy of the old value – which is why prefix increment is preferred for iterators and class types.
#include <iostream>
class Counter {
int v_ = 0;
public:
Counter& operator++() { ++v_; return *this; } // prefix: ++c – returns the updated object
Counter operator++(int) { Counter old = *this; ++v_; return old; } // postfix: c++ – dummy int, returns old value
int value() const { return v_; }
};
int main() {
Counter c;
Counter a = c++; // a gets the old value
Counter b = ++c; // b gets the new value
++ ++c; // prefix returns a reference, so it can be chained
std::cout << a.value() << ' ' << b.value() << ' ' << c.value() << '\n';
return 0;
}
0 2 4
Conversion operators
operator T() converts an object to type T. Mark it explicit unless the conversion is completely natural and safe. An explicit operator bool is still used automatically in conditions (if, while, &&, !), but not in arithmetic.
#include <iostream>
#include <string>
class Rupees {
long paise_;
public:
explicit Rupees(double r) : paise_(static_cast<long>(r * 100 + 0.5)) {}
explicit operator double() const { return paise_ / 100.0; } // only with a cast
explicit operator bool() const { return paise_ != 0; } // used in if (...) automatically
operator std::string() const { return "Rs " + std::to_string(paise_ / 100) + "." + std::to_string(paise_ % 100 / 10) + std::to_string(paise_ % 10); }
};
int main() {
Rupees fee(1499.5), zero(0);
std::string s = fee; // implicit conversion allowed (not explicit)
double d = static_cast<double>(fee); // explicit conversion needs a cast
std::cout << s << ' ' << d << '\n';
if (fee && !zero) std::cout << "fee due, nothing refunded\n"; // explicit bool works in conditions
// int n = fee; error: no implicit conversion
return 0;
}
Rs 1499.50 1499.5 fee due, nothing refunded
Dereference and member access
Overloading * and -> makes a class behave like a pointer – the basis of std::unique_ptr, std::shared_ptr and iterators. operator-> must return a pointer (or an object that itself overloads ->).
#include <iostream>
#include <string>
// A tiny owning pointer: overloading -> and * lets it be used like a raw pointer
template <typename T>
class Owner {
T* p_;
public:
explicit Owner(T* p) : p_(p) {}
~Owner() { delete p_; }
Owner(const Owner&) = delete;
Owner& operator=(const Owner&) = delete;
T& operator*() const { return *p_; }
T* operator->() const { return p_; }
};
struct User { std::string name; int age; };
int main() {
Owner<User> u(new User{"Asha", 21});
u->age += 1; // calls operator->, then ->age on the returned pointer
std::cout << (*u).name << ' ' << u->age << '\n';
return 0;
}
Asha 22
User-defined literals
operator""_suffix creates literals such as 12.5_km. The standard library provides "text"s, 10min, 2h and more; your own suffixes must start with an underscore.
#include <chrono>
#include <iostream>
#include <string>
struct Km { double v; };
constexpr Km operator""_km(long double x) { return Km{static_cast<double>(x)}; }
constexpr Km operator""_m(unsigned long long x) { return Km{x / 1000.0}; }
constexpr Km operator+(Km a, Km b) { return Km{a.v + b.v}; }
int main() {
using namespace std::literals; // standard literals: "…"s, 10min, 2h …
Km trip = 12.5_km + 750_m;
auto t = 1h + 30min;
std::string s = "hello"s + " world";
std::cout << trip.v << " km, " << t.count() << " min, " << s.size() << " chars\n";
return 0;
}
13.25 km, 90 min, 11 chars
Which operators can be overloaded?
| Can be overloaded | Cannot be overloaded |
|---|---|
+ - * / % ^ & | ~ ! = < > += -= *= /= %= ^= &= |= << >> >>= <<= == != <= >= <=> && || ++ -- , ->* -> () [] new delete new[] delete[] co_await | :: . .* ?: sizeof typeid alignof casts like static_cast |
Overloading &&, || and the comma operator is legal but discouraged: the overloaded versions lose short-circuit evaluation.
Common mistakes
- Surprising meanings –
+that subtracts, or<<that modifies the object. - Returning by value from += or prefix ++ – breaks chaining; return
*thisby reference. - Returning a reference to a local from
+– return by value. - Member operator<< – then you would have to write
obj << cout. - Asymmetric operators – a member
operator*(double)makesv * 2work but not2 * v. - Implicit conversion operators causing ambiguous overloads – prefer explicit.
- Inconsistent operators –
==and<that disagree, or+that differs from+=.
Key points to remember
- An operator is a function named
operator@. - =, [], (), -> must be members; << and >> for streams must be non-members.
- Implement + via +=; return *this by reference from compound and prefix operators.
- Default
<=>and==in C++20 for member-wise comparisons. - Postfix ++ takes a dummy int and returns the old value.
- Precedence and arity never change; ::, ., .*, ?: and sizeof cannot be overloaded.
Frequently asked questions
Should an operator be a member or a non-member?
Members for operators that must be members (=, [], (), ->) and for those that modify the left operand (+=, ++). Non-members (often friends) for symmetric binary operators (+, ==, <) and for stream operators.
Is operator overloading a form of polymorphism?
Yes – compile-time (static) polymorphism, like function overloading.
What is the difference between function overloading and operator overloading?
Function overloading gives several functions the same name with different parameters; operator overloading defines what an operator means for a user-defined type. Both are resolved at compile time.
Where can I learn more?
Read C++ Operator Overloading and C++ Classes and Objects, then practise with the exercises below.