With built-in types, operators feel natural: a + b, x == y, std::cout << n. But suppose you write a Complex class for complex numbers. Without extra work, you would have to write c = a.add(b), which is clumsy. Wouldn't it be nicer to write c = a + b?
C++ lets you do exactly that. You can give operators a meaning for your own classes. This is called operator overloading, and it is why std::string supports s1 + s2, why std::cout << x works, and why v[i] works on a std::vector.
In this chapter we will cover the rules, member vs non-member operators, arithmetic, unary, increment, comparison (including C++20's <=>), stream, subscript (including C++23's multidimensional subscript), function call, assignment and conversion operators.
What Is Operator Overloading?
Operator overloading means defining a special function named
operator@(where@is the operator symbol) so that the operator works with objects of a user-defined type. When the compiler sees the operator applied to such objects, it calls that function.
It is a form of compile-time (static) polymorphism: the same symbol + does different things for int, double, std::string and Complex, and the compiler decides which function to call by looking at the operand types, just like Function Overloading.
The key mental model: an operator expression is just a function call in disguise.
Expression Member form Non-member form
a + b → a.operator+(b) or operator+(a, b)
-a → a.operator-() or operator-(a)
a == b → a.operator==(b) or operator==(a, b)
a[i] → a.operator[](i) (member only)
a(x, y) → a.operator()(x, y) (member only)
a = b → a.operator=(b) (member only)
Rules You Cannot Break
- You cannot create new operators. There is no
**for power or<>. - You cannot change precedence, associativity (grouping) or the number of operands.
a + b * cstill meansa + (b * c), and binary/always takes two operands. - At least one operand must be of a class or enumeration type. You cannot redefine
+for twoints. - These operators cannot be overloaded:
::(scope resolution),.(member access),.*(pointer-to-member access) and?:(conditional). Alsosizeof,alignof,typeidand the cast keywords such asstatic_castare not overloadable. - These must be non-static member functions:
=,(),[]and->. (Since C++23,operator()andoperator[]may also be static members; they still cannot be non-members.) - Overloaded
&&and||lose short-circuit evaluation: both operands are always evaluated. That is why you should almost never overload them (or the comma operator). - Default arguments are not allowed in operator functions, except for
operator()(and, since C++23,operator[]).
Almost everything else can be overloaded: arithmetic (+ - * / %), bitwise (& | ^ ~ << >>), comparison (== != < > <= >= <=>), logical !, assignment and compound assignment (= += -= ...), ++ --, [] () -> ->*, new/delete, and conversion operators.
Your First Overloaded Operator (Member Function)
#include <iostream>
class Complex {
double re, im;
public:
Complex(double r = 0, double i = 0) : re(r), im(i) {}
// Member operator: the LEFT operand is *this
Complex operator+(const Complex& rhs) const {
return Complex(re + rhs.re, im + rhs.im);
}
void print() const { std::cout << re << " + " << im << "i\n"; }
};
int main() {
Complex a(1, 2), b(3, 4);
Complex c = a + b; // the compiler turns this into a.operator+(b)
Complex d = a.operator+(b); // the same call written by hand
c.print();
d.print();
}
Output:
4 + 6i
4 + 6i
When operator+ is a member, the left operand is the object the function is called on (*this), and the right operand is the single parameter. So a binary member operator has one parameter and a unary member operator has none.
The parameter is const Complex& to avoid a copy, and the function is const because a + b must not modify a.
The Problem with Member Operators: Symmetry
Our constructor has default arguments, so an int or double can be implicitly converted to Complex. That makes a + 5 work. But what about 5 + a?
#include <iostream>
class Complex {
double re, im;
public:
Complex(double r = 0, double i = 0) : re(r), im(i) {}
Complex operator+(const Complex& rhs) const {
return Complex(re + rhs.re, im + rhs.im);
}
};
int main() {
Complex a(1, 2);
Complex b = a + 5; // OK: a.operator+(Complex(5))
Complex c = 5 + a; // error: 5 is an int, it has no operator+ member
}
Compiler error (g++ 15, abridged):
o2.cpp:15:19: error: no match for ‘operator+’ (operand types are ‘int’ and ‘Complex’)
5 + a would have to be 5.operator+(a), and int has no member functions. Implicit conversions are never applied to the object on which a member function is called. A non-member operator+(const Complex&, const Complex&) treats both operands equally, so the compiler can convert either side.
The Canonical Pattern: += as Member, + as Non-Member
Experienced C++ programmers implement arithmetic operators this way:
operator+=is a member. It modifies the left operand and returns*thisby reference (like the built-in+=, which yields its left operand).operator+is a non-member (often a hidden friend, see Friend Functions & Classes). It takes the left operand by value (that copy becomes the result), applies+=, and returns it.
This keeps the arithmetic logic in one place and makes + symmetric. Here is a complete Complex class:
#include <iostream>
class Complex {
double re, im;
public:
Complex(double r = 0, double i = 0) : re(r), im(i) {}
// Compound assignment: member, modifies *this, returns *this by reference
Complex& operator+=(const Complex& rhs) {
re += rhs.re;
im += rhs.im;
return *this;
}
// Binary +: non-member (hidden friend), implemented using +=
friend Complex operator+(Complex lhs, const Complex& rhs) {
lhs += rhs; // lhs is already a copy, so we can modify it
return lhs;
}
// Unary minus: returns a new value
Complex operator-() const { return Complex(-re, -im); }
// Equality (C++20 automatically provides != from this)
friend bool operator==(const Complex&, const Complex&) = default;
// Output
friend std::ostream& operator<<(std::ostream& os, const Complex& c) {
return os << c.re << (c.im < 0 ? " - " : " + ")
<< (c.im < 0 ? -c.im : c.im) << 'i';
}
};
int main() {
Complex a(1, 2), b(3, -4);
std::cout << "a + b = " << a + b << '\n';
std::cout << "5 + a = " << 5 + a << '\n'; // works now: Complex(5) + a
std::cout << "-a = " << -a << '\n';
a += b;
std::cout << "a after += : " << a << '\n';
std::cout << std::boolalpha;
std::cout << "a == b ? " << (a == b) << '\n';
std::cout << "a != b ? " << (a != b) << '\n';
}
Output:
a + b = 4 - 2i
5 + a = 6 + 2i
-a = -1 - 2i
a after += : 4 - 2i
a == b ? false
a != b ? true
Let's trace a few lines:
a + b= (1 + 3) + (2 − 4)i = 4 − 2i.5 + a: the compiler converts 5 toComplex(5, 0)becauseoperator+is a non-member, giving 6 + 2i.-acalls the unary memberoperator-(), which has no parameters.operator==is defaulted (C++20): the compiler compares members in order. In C++20 the compiler also rewritesa != bas!(a == b), so we did not have to write!=.operator<<must be a non-member because its left operand isstd::ostream. It returns the stream by reference to allow chaining.
Increment and Decrement: Prefix vs Postfix
++c and c++ use the same symbol, so how does the compiler tell them apart? By a rule that looks odd at first: the postfix version takes a dummy int parameter, which is never used.
Prefix ++c | Postfix c++ | |
|---|---|---|
| Declaration (member) | T& operator++() | T operator++(int) |
| Returns | The object itself, by reference | A copy of the old value, by value |
| Extra copy? | No | Yes (the saved old value) |
#include <iostream>
class Counter {
int value;
public:
explicit Counter(int v = 0) : value(v) {}
// Prefix ++c : increment, then return the object itself
Counter& operator++() {
++value;
return *this;
}
// Postfix c++ : the dummy int parameter marks it as postfix
Counter operator++(int) {
Counter old = *this; // save the old value
++(*this); // reuse prefix ++
return old; // return the OLD value by value
}
int get() const { return value; }
};
int main() {
Counter c(5);
Counter x = ++c; // c becomes 6, x gets 6
std::cout << "x = " << x.get() << ", c = " << c.get() << '\n';
Counter y = c++; // y gets 6, c becomes 7
std::cout << "y = " << y.get() << ", c = " << c.get() << '\n';
++ ++c; // prefix returns a reference, so this chains: c = 9
std::cout << "c = " << c.get() << '\n';
}
Output:
x = 6, c = 6
y = 6, c = 7
c = 9
Because postfix must make a copy, prefer ++it over it++ for class types (such as iterators) when you don't need the old value. For int the compiler optimizes both the same way.
Comparison Operators and the C++20 Spaceship <=>
Before C++20, a class that needed ordering required six functions: ==, !=, <, <=, >, >=. C++20 introduced the three-way comparison operator <=> (nicknamed the spaceship). a <=> b returns an object that compares less than, equal to, or greater than 0.
#include <compare>
#include <iostream>
struct Version {
int major, minor, patch;
// C++20: one line gives <, <=, >, >=, == and !=
auto operator<=>(const Version&) const = default;
};
int main() {
Version v1{1, 4, 2}, v2{1, 10, 0};
std::cout << std::boolalpha;
std::cout << (v1 < v2) << '\n'; // compares major, then minor, then patch
std::cout << (v1 == v2) << '\n';
std::cout << (v1 >= Version{1, 4, 2}) << '\n';
auto r = v1 <=> v2;
std::cout << (r < 0 ? "v1 is older" : r > 0 ? "v1 is newer" : "same") << '\n';
}
Output:
true
false
true
v1 is older
How this works:
- A defaulted
<=>compares the members lexicographically in declaration order: firstmajor(1 vs 1, equal), thenminor(4 vs 10, less), sov1 < v2. Note it is numeric comparison, so 4 < 10, unlike comparing the strings "1.4" and "1.10". - The compiler rewrites
v1 < v2as(v1 <=> v2) < 0, and similarly for<=,>,>=. - Defaulting
<=>also implicitly declares a defaulted==, and!=is rewritten from==. - For
intmembers the result type isstd::strong_ordering(from<compare>). Withdoublemembers it would bestd::partial_ordering, because NaN is unordered.
Stream Operators << and >>
#include <iostream>
class Point {
int x = 0, y = 0;
public:
friend std::ostream& operator<<(std::ostream& os, const Point& p) {
return os << '(' << p.x << ", " << p.y << ')';
}
friend std::istream& operator>>(std::istream& is, Point& p) {
return is >> p.x >> p.y; // reads into the object, so p is non-const
}
};
int main() {
Point p, q;
std::cin >> p >> q;
std::cout << p << " and " << q << '\n';
}
Input:
3 4 -1 8
Output:
(3, 4) and (-1, 8)
Rules of thumb: operator<< takes the object by const&; operator>> takes it by non-const reference because it fills it in. Both take and return the stream by reference, because streams cannot be copied and chaining needs the same stream back.
Subscript Operator []
operator[] should return a reference so that a[i] = x can modify the element. Usually you write two overloads: a non-const one for modifiable objects and a const one for const objects.
#include <cstddef>
#include <iostream>
class IntArray {
int data[5] = {10, 20, 30, 40, 50};
public:
// Non-const version: returns a reference so a[i] = x works
int& operator[](std::size_t i) { return data[i]; }
// Const version: used for const objects; read-only
const int& operator[](std::size_t i) const { return data[i]; }
};
class Matrix {
int cells[2][3] = {{1, 2, 3}, {4, 5, 6}};
public:
// C++23: multidimensional subscript m[r, c]
int& operator[](std::size_t r, std::size_t c) { return cells[r][c]; }
};
int main() {
IntArray a;
a[2] = 99; // calls the non-const operator[]
const IntArray& ca = a;
std::cout << ca[2] << '\n'; // calls the const operator[]
Matrix m;
m[1, 2] = 60;
std::cout << m[0, 1] << ' ' << m[1, 2] << '\n';
}
Output:
99
2 60
Before C++23, operator[] could take only one argument, so matrix classes used m(r, c) or returned a proxy row for m[r][c]. C++23 allows any number of subscripts, so m[1, 2] calls operator[](1, 2). (In C++20 and earlier, m[1, 2] meant the comma operator; that use inside brackets was deprecated in C++20 and repurposed in C++23.) Like built-in arrays, our operator[] does no bounds checking; an out-of-range index is undefined behavior.
Function Call Operator () and Functors
A class that overloads operator() produces objects that can be called like functions. These are called function objects or functors. Unlike plain functions, they can carry state (here, factor).
#include <iostream>
// A function object (functor): an object you can "call"
class Multiplier {
int factor;
public:
explicit Multiplier(int f) : factor(f) {}
int operator()(int x) const { return x * factor; }
};
int main() {
Multiplier twice(2), thrice(3);
std::cout << twice(10) << ' ' << thrice(10) << '\n';
}
Output:
20 30
Functors are used heavily with STL algorithms (for example as custom comparators), and every lambda expression is actually an object of a compiler-generated class with an operator(). You will see both in later chapters.
The Assignment Operator =
If you don't write one, the compiler generates a copy assignment operator that assigns member by member. That is fine for classes whose members manage themselves (int, std::string, std::vector). But if your class owns a raw resource, such as memory from new[], member-wise assignment copies only the pointer, causing two objects to share and later both delete[] the same memory.
A correct copy assignment operator must:
- Be a member function, taking
const T&. - Handle self-assignment (
a = a) safely. - Release the old resource and make a deep copy.
- Return
*thisby reference soa = b = cworks.
#include <algorithm>
#include <cstddef>
#include <iostream>
class Buffer {
std::size_t n;
int* data;
public:
explicit Buffer(std::size_t size) : n(size), data(new int[size]{}) {}
Buffer(const Buffer& other) : n(other.n), data(new int[other.n]) {
std::copy(other.data, other.data + n, data);
}
~Buffer() { delete[] data; }
// Copy assignment: deep copy, safe for self-assignment, returns *this
Buffer& operator=(const Buffer& other) {
if (this == &other) return *this; // guard against a = a
int* fresh = new int[other.n]; // allocate first: if this throws, *this is unchanged
std::copy(other.data, other.data + other.n, fresh);
delete[] data; // only now release the old memory
data = fresh;
n = other.n;
return *this;
}
int& at(std::size_t i) { return data[i]; }
};
int main() {
Buffer a(3), b(3);
a.at(0) = 7;
b = a; // operator=
a.at(0) = 1; // changing a must not change b (deep copy)
std::cout << a.at(0) << ' ' << b.at(0) << '\n';
a = a; // self-assignment is harmless
std::cout << a.at(0) << '\n';
}
Output:
1 7
1
Notice the order: we allocate the new array before deleting the old one. If new throws, the object is still in its old valid state. A popular alternative is the copy-and-swap idiom (take the parameter by value and swap with it).
This class has a destructor, a copy constructor and a copy assignment operator together, which is the Rule of Three from Constructors & Destructors: if a class needs one of them, it almost certainly needs all three. C++11 extends this to the Rule of Five by adding the move constructor and move assignment (see Move Semantics & Rvalue References), and the Rule of Zero says the best design is to let members like std::vector manage resources so you need none of them.
Conversion Operators
A conversion operator lets an object be converted to another type. It is written operator Type() const, with no return type before the keyword (the type is in the name), and it must be a member.
#include <iostream>
class Rational {
int num, den;
public:
Rational(int n, int d) : num(n), den(d) {}
// explicit conversion to bool: true if the value is non-zero
explicit operator bool() const { return num != 0; }
// implicit conversion to double
operator double() const { return static_cast<double>(num) / den; }
};
int main() {
Rational half(1, 2), zero(0, 5);
if (half) std::cout << "half is non-zero\n"; // explicit bool is allowed in conditions
if (!zero) std::cout << "zero is zero\n";
double d = half; // implicit conversion to double
std::cout << d << '\n';
std::cout << half + 1 << '\n'; // surprise: half silently becomes 0.5
bool b = static_cast<bool>(half); // explicit conversion: OK
std::cout << std::boolalpha << b << '\n';
}
Output:
half is non-zero
zero is zero
0.5
1.5
true
Marking a conversion explicit (allowed since C++11) prevents surprising implicit conversions. An explicit operator bool still works in conditions like if, while, !, && and || (contextual conversion), but is never used silently in arithmetic or initialization. This is how standard types such as streams and std::unique_ptr support if (obj). The non-explicit operator double, on the other hand, kicks in silently: half + 1 compiled and printed 1.5 without us asking for any conversion. Sometimes that is what you want, but often it hides bugs. Prefer explicit for conversion operators unless the implicit conversion is truly natural.
Member or Non-Member? A Quick Guide
| Operator | Recommended form | Why |
|---|---|---|
=, [], (), ->, conversions | Member (required) | The language requires it |
+=, -=, *= ... | Member | Modifies the left operand |
Unary -, !, ~, ++, -- | Member | Operates on a single object |
Binary + - * / | Non-member (hidden friend) | Symmetric conversions on both operands |
== <=> and the other comparisons | Member or hidden friend; C++20 rewrites make either symmetric | Often just = default |
<<, >> for streams | Non-member (usually friend) | Left operand is a stream, not our class |
And the golden rule of operator overloading: make the operator behave like it does for int. + should not modify its operands, == should be consistent with !=, and += should return a reference. Surprising operators make code harder to read, not easier.
Common Mistakes
- Returning by value from
+=,=or prefix++. ReturnT&(*this); otherwise chaining like(a += b) += cmodifies a temporary. - Returning a reference to a local from
operator+, as inComplex& operator+(...). The local dies when the function returns, leaving a dangling reference. Binary arithmetic operators return by value. - Making
operator<<a member, which would force the unnatural syntaxobj << std::cout. - Forgetting
conston operators that don't modify the object, so they can't be used on const objects. - Mixing up the postfix dummy parameter: postfix is
operator++(int), prefix isoperator++(). - Overloading
&&,||or,, which lose short-circuit evaluation and confuse readers. - Not handling self-assignment in a hand-written
operator=that deletes memory before copying.
Interview / Exam Questions
1. Name four operators that cannot be overloaded.
::, ., .* and ?:. (sizeof, alignof and typeid also cannot be overloaded.)
2. How does the compiler distinguish prefix and postfix ++?
The postfix version is declared with a dummy int parameter: T operator++(int). The prefix version has no parameter (as a member): T& operator++().
3. Why should binary operator+ usually be a non-member?
So that implicit conversions can apply to both operands. As a member, 5 + c fails because the left operand 5 cannot be converted to the class type for a member call. As a non-member, both sides are ordinary parameters.
4. How many parameters does a member operator- take for unary minus? For binary minus?
Zero for unary minus (-a → a.operator-()) and one for binary minus (a - b → a.operator-(b)). As non-members they take one and two respectively.
5. Which operators must be member functions?
operator=, operator(), operator[], operator->, and conversion operators.
6. What does auto operator<=>(const T&) const = default; give you in C++20?
Lexicographic member-wise three-way comparison. The compiler rewrites <, <=, >, >= in terms of it, also implicitly declares a defaulted operator==, and rewrites != from ==. So all six comparisons work.
7. Can operator overloading change the precedence of + relative to *?
No. Precedence, associativity and the number of operands are fixed by the grammar. a + b * c always means a + (b * c), whatever the types.
Summary
- Operator overloading defines functions named
operator@; an expression likea + bbecomesa.operator+(b)oroperator+(a, b). - You cannot invent operators, change precedence or arity, or overload
::..*?:. =[]()->must be members; stream operators must be non-members.- Implement
+=as a member returning*this, and+as a non-member built on+=. - Postfix
++uses a dummyintand returns the old value by value; prefix returns a reference. - C++20's defaulted
<=>gives all six comparisons; C++23 adds multidimensionaloperator[]. - A hand-written
operator=must deep-copy, survive self-assignment and return*this(Rule of Three/Five/Zero). - Prefer
explicitconversion operators.
Next we move to one of the pillars of object-oriented programming: Inheritance.