Careers[careers]

C++ Operator Overloading Explained: A Complete Guide

Section
Careers [careers]
Published
Length
12 min read
In this answer8 clauses
  1. 1C++ Operator Overloading Basics
  2. 1.1How operators work as special functions
  3. 1.2Which operators you can and cannot overload
  4. 1.3Grouping operators by operand count
  5. 1.4Keep overloaded operators intuitive and predictable
  6. 2Choosing Member or Non-member Operators
  7. 2.1How member operators actually work
  8. 2.2Non-member operators and friend access
  9. 2.3Why symmetry matters for implicit conversions
  10. 2.4Operators the compiler requires as members
  11. 2.5Operators you can’t make members
  12. 2.6Quick rules for picking the form
  13. 3Doing Arithmetic and Compound Assignment
  14. 3.1Binary arithmetic that returns new objects
  15. 3.2Compound assignment that changes the left side
  16. 4Handling Unary, Increment and Decrement Operators
  17. 4.1Unary operators as member functions
  18. 4.2Telling prefix and postfix increment apart
  19. 5Sending Objects to a Stream with <<
  20. 5.1Making << output chain cleanly
  21. 6Teaching Objects How to Compare
  22. 6.1Hand-coding your own comparison operators
  23. 6.2Generating all comparisons with C++20 <=>
  24. 7The Copy Assignment Operator
  25. 7.1Implementing copy assignment in your classes
  26. 7.2Common mistakes in assignment code
  27. 8When Your Types Convert Implicitly
  28. 8.1Writing conversion operators with care
  29. 8.2Using explicit with one-argument constructors
  30. 8.3Temporary objects and their short lives

Abstract

C++ operator overloading lets custom types use familiar symbols such as `+`, `==` and `<<` by defining what those operations mean. Keep each operator intuitive, choose a member or non-member based on which operand must change and where conversions should work, and use `explicit` to prevent unintended conversions. In practice, clear operator behavior makes code easier to read and review; C++20’s defaulted `<=>` can generate comparisons, while earlier standards require them to be written separately.

Brass sorting machine combines arrows and cubes into one form, symbolizing integration.
Figure 1 — Brass sorting machine combines arrows and cubes into one form, symbolizing integration.

Think of comparing two shipping crates by weight. Writing if (crate_a < crate_b) reads naturally only if your class supports it. That’s operator overloading: giving your own type the meaning of an operator like + or <, so it reads as naturally as an int.

The right approach depends on which standard you compile with.

We’ll cover the basics, member versus non-member choice, the common operators, and how C++20’s spaceship operator (<=>) generates most comparisons for you. Along the way, we’ll flag interview pitfalls and review tips, each dated to its standard.

C++ Operator Overloading Basics

Operator overloading lets your own types use the symbols you already know, so a + b can work on a matrix as naturally as on an int. Here’s what happens under the hood and what you can change.

How operators work as special functions

An operator is a specially named function. When you write a + b, the compiler rewrites it as a call to operator+. You declare one with the operator keyword, and your type then reads like a built-in.

Picture a game engine programmer whose Vec2 type overloads + and *. The physics line reads position = position + velocity * dt;, so a reviewer can check it against the design doc at a glance.

Which operators you can and cannot overload

Most everyday operators can be overloaded:

  • Arithmetic: +, -, *, /, %
  • Relational: ==, !=, <, >, <=, >=
  • Logical: !, &&, ||

Four are off limits: ::, ., .* and ?:, so . always means member access. You also can’t invent new operators. The operand count (arity) and precedence stay put: a binary operator stays binary, and a * b + c still multiplies first.

You change what an operator does, not how the compiler parses it.

Grouping operators by operand count

Every operator has a fixed operand count, so each falls into one group:

  • Unary: one operand, like the ! in !ready.
  • Binary: two operands, like a + b.
  • Ternary: three operands. C++ has just one, ?:, and it’s on the can’t-overload list.

Count first: the number tells you what your overload must accept.

Keep overloaded operators intuitive and predictable

The compiler accepts any meaning you give an operator, so the real test is whether a teammate can guess that meaning from the symbol.

  • Preserve the expected meaning. + should combine values, and == should answer whether two values match.
  • Avoid surprising behavior. If + quietly writes to a log file, the next reader pays for it.
  • Overload only for good reason. If a named function like add reads just as clearly, use that.

The classic interview question is when to overload. Overload when the operator has an obvious meaning for your type and the code reads better with it.

A Vec2 adding positions passes that test, but a += that appends a database row fails, because the symbol hides a write. Clarity wins.

Choosing Member or Non-member Operators

Every overloaded operator lives inside the class or beside it, and that choice decides which private members it can touch and which conversions apply. Here’s how we make the call.

How member operators actually work

When you write a member operator, the object on the left is *this and the rest of the expression supplies the arguments. Consider a payments engineer’s Money class. Her operator+ is a member, so it reads the private cents field directly.

  • A binary member takes one parameter, the right operand.
  • Members get direct private access, so no friend declaration is needed.
  • Any member that doesn’t modify the object should be const-qualified.

That last rule pays off: a const Money total can still be added to, and the signature promises the inputs stay untouched.

A woman's hand rests on an open ledger as a coin slides toward it, illustrating immutable records and precise accounting.
Figure 2 — A woman's hand rests on an open ledger as a coin slides toward it, illustrating immutable records and precise accounting.

Non-member operators and friend access

A non-member operator is a free function where both operands are explicit parameters, so a + b becomes operator+(a, b) and the symmetry lives in the signature.

If that function needs private data, declare it a friend inside the class. Keep that list short, since every friend is another place that can touch the internals.

Helper operators that use only the public interface need no friend at all. If operator- can be built from += and a public accessor, the class’s internals stay sealed.

Why symmetry matters for implicit conversions

This is where the choice bites. Suppose Money has a converting constructor from int and operator+ is a member. Then money + 50 compiles, because the right operand converts.

But 50 + money fails: a member never converts its left operand, and an int has no member operator+ to call.

Mirrored non-member overloads fix this. Declare operator+ as a non-member taking two const Money& parameters, and both operand orders go through the same conversion, provided the constructor isn’t explicit. Symmetry is the fix.

Operators the compiler requires as members

Four operators must be members: =, [], (), and ->. Declare a non-member version of any of them and the compiler rejects the code, so there’s no choice to make.

That list explains operator->, which is why smart pointers and iterator-style wrappers define it inside the class. A smart pointer typically pairs it with operator*, which returns the pointed-to object.

Unary * isn’t on the list, but the quick rules below point it toward a member too.

Operators you can’t make members

Some operators have a left operand you don’t own, so a member is impossible:

  • Stream output. In std::cout << money, the left operand is an std::ostream, and you can’t add members to it. Write operator<< as a non-member taking std::ostream& and your type, then return the stream so chaining still works.
  • Fundamental types on the left. In 50 + money, the int has no class to hold a member.
  • Classes you cannot modify. A type from a library you don’t control leaves a non-member as the only option.

Quick rules for picking the form

Check these when a new operator shows up in review:

  • Modifies the left operand. Make it a member. Compound assignment such as += works this way because it changes the object it’s called on.
  • Symmetric binary. Make it a non-member. Operators like + should accept conversions on both sides.
  • Unary. Make it a member. Unary -, ! and * are usually written inside the class.

Before you commit, ask the question underneath all of them: does the left side change? That answer usually settles the form.

Doing Arithmetic and Compound Assignment

Arithmetic and compound assignment look alike, but they make different promises. One builds a new value, and the other changes an existing one. Get that split right and you’ll write operators that behave the way callers expect.

Binary arithmetic that returns new objects

Picture a game engine programmer adding a Vec2 type for particle positions. In auto next = pos + velocity * dt;, pos should stay untouched while next gets a fresh vector. A binary operator+ does exactly that.

  • Return new object by value. Build a local result and return it. The caller gets its own object.
  • Take const reference parameters. Declare the operands as const Vec2& so the operator reads them without copying them first.
  • Inputs left unmodified. Neither operand changes. Marking the parameters const enforces that promise.

Compound assignment that changes the left side

This one does the opposite: += updates the object on its left, while + creates a new one. Think of a firmware developer keeping a running total of sensor readings. total += reading; updates total directly, so the review shows one clear change.

  • Modify left operand. operator+= writes the result into the left-hand object, so it can’t be const.
  • Return reference to *this. Return *this as Vec2& so chains like a += b += c work, as they do for built-in types.
  • Non-const member. Declare operator+= as a non-const member function. You can then build operator+ on top of it, so the logic lives in one place.

Same family of symbols, different promise. Check which one your diff makes.

A hand rests on a tally counter with one digit highlighted in vermilion, next to a circuit board and a faint outline of a new object.
Figure 3 — A hand rests on a tally counter with one digit highlighted in vermilion, next to a circuit board and a faint outline of a new object.

Handling Unary, Increment and Decrement Operators

Unary operators act on one operand, and increment and decrement add a wrinkle you’ll want to get right. Here’s how to write each one.

Unary operators as member functions

A unary operator takes no explicit parameters when it’s a member function. The operand is the current object, so negating a vector looks like this:

Vector2 operator-() const { return {-x, -y}; }

Writing -v calls v.operator-(), with *this standing in for the operand. Subscript and call operators must be members too. operator[] typically takes one index and returns a reference, while operator() takes whatever arguments the call needs.

Telling prefix and postfix increment apart

Both forms share the name operator++, so C++ uses a dummy parameter: an unnamed int that exists only to tell the postfix version apart. Callers never pass it; the compiler supplies a value.

Prefix hands back the updated object by reference, so ++++id chains. Postfix hands back the old value by copy.

FrameId& operator++() { ++value; return *this; }

FrameId operator++(int) { FrameId old = *this; ++(*this); return old; }

Consider a game engine programmer who wraps a frame counter in FrameId. The hot loop only ever writes ++id, so the prefix form skips the temporary copy that postfix would build on every tick.

Let postfix call prefix, so the logic lives in one place. Less code to review.

Sending Objects to a Stream with <<

Printing your own type should feel as natural as printing an int. Getting the operator’s signature right does most of the work.

Making << output chain cleanly

Write the operator as a non-member function that takes a std::ostream& on the left and your type on the right. Because the stream sits on the left, the operator has to live outside your class, not inside it.

Take the stream by non-const reference so you can write to it, and take your object by const& so printing never changes it.

Return the stream itself, as std::ostream&, so the next << in the chain has something to act on:

[Example 1:
#include <ostream>

struct Point { int x; int y; };

std::ostream& operator<<(std::ostream& os, const Point& p) {
    return os << "(" << p.x << ", " << p.y << ")";
}

— end example]

Return void instead, and the compiler rejects std::cout << a << b, since the first << leaves nothing for the second to act on. Keep the return.

If the operator needs private members, declare it a friend inside the class, then define it outside as a non-member. Reach for that only when you truly need it, since a public getter often does the job and keeps the class boundary intact.

Consider a firmware developer logging a sensor reading with log << "temp=" << reading << '\n';. Once the operator exists, that line reads like any built-in type, and the struct gains no logging code of its own.

Teaching Objects How to Compare

Comparing two objects is usually the first operator a custom type needs, and the way you write it depends on the standard you compile with.

Hand-coding your own comparison operators

Before C++20, you write == and < yourself, and each one has three rules to follow:

  • Return bool. operator== and operator< return bool, so if (a < b) reads the way it looks.
  • Keep ordering consistent. operator< must define a strict weak ordering, meaning a < a is always false and the comparison is transitive. Break that and std::sort misbehaves.
  • Tie-break on later members. Consider a library maintainer with a Version type holding major, minor and patch. Compare major first, move to minor only when the majors tie, and to patch only when both tie. So 1.2.9 sorts before 1.3.0.

Generating all comparisons with C++20 <=>

C++20 adds the three-way comparison operator, <=>, nicknamed the spaceship operator, and one <=> generates <, <=, > and >=. Write it as auto operator<=>(const Version&) const = default; and the compiler handles the rest.

It compares members in declaration order, not alphabetical order, and a defaulted <=> also declares == for you. Reorder the fields and you reorder the sort.

C++20 also uses rewritten and reversed candidates: a != b uses your ==, and 5 == obj can call a member operator== on obj’s type. For the maintainer, four hand-written comparisons become one line, and the tie-break code goes with them.

Prefer defaulted <=> in new code. It’s shorter, it picks up new members without edits, and reviewers see the order at a glance. Keep hand-written operators for code that must still build as C++17, or for types whose order isn’t plain member order.

A drafting desk shows a balance beam with inequality symbols radiating from its pivot, alongside index cards and drafting tools.
Figure 4 — A drafting desk shows a balance beam with inequality symbols radiating from its pivot, alongside index cards and drafting tools.

The Copy Assignment Operator

Copy assignment runs when an existing object takes on another’s value, as in a = b;. Here’s how to write it and where it goes wrong.

Implementing copy assignment in your classes

If you don’t declare one, the compiler generates a copy assignment operator that copies each member. That’s fine for plain values, but once a class owns a resource, like a raw heap buffer, the generated version copies the pointer, not the data. Knowing what a pointer is makes this copy much easier to spot.

Picture a firmware developer whose SensorFrame holds a uint8_t*. A teammate assigns one frame to another during a retry, and both objects now point at the same buffer. Two objects, one buffer, one double free.

A custom operator that copies the bytes fixes it.

Write it as Type& operator=(const Type& other), returning *this by reference so a = b = c; chains.

Common mistakes in assignment code

Self-assignment (a = a;, or two references to one object) breaks a naive operator. Release your buffer before reading other, and you free the data you’re copying, so guard with if (this != &other).

Order matters too: copy into the new resource before releasing the old one. Delete first, and a throwing allocation leaves a dangling pointer.

The copy-and-swap idiom takes the parameter by value, swaps members with *this, and lets the temporary release the old state. The copy comes first, so self-assignment and ordering are handled together, as long as the swap doesn’t throw.

Often the best operator is the one you don’t write.

Under the rule of zero, members like std::vector or std::string already copy and clean up correctly, so a game engine programmer who swaps a hand-rolled string class for std::string drops the operator and its self-assignment bug with it.

When Your Types Convert Implicitly

Implicit conversions save typing until they quietly change what your code means. Two tools control them: conversion operators and constructors.

Writing conversion operators with care

Say a Connection class wants to work in an if. Mark its bool conversion explicit and if (conn) still works, but int n = conn; doesn’t. Leave it implicit and conn + 1 compiles, because the bool quietly promotes to an int.

Implicit conversions are also prone to ambiguities: when two could apply, overload resolution can fail. Keep the body trivial, with no side effects, so the conversion’s meaning is obvious.

Review flag: any non-explicit conversion operator in a diff deserves a question: did the author want it, or just forget the keyword?

Using explicit with one-argument constructors

A single-argument constructor defines a conversion from its argument type to your type. Consider an embedded firmware developer with a Port type whose constructor rejects out-of-range numbers.

Without explicit, a stray int passed to open_socket() silently builds a temporary Port, and the call hides it. Mark the constructor explicit, and the caller must write open_socket(Port{8080}).

The question is less whether the call compiles and more whether the conversion was intended. Limit single-argument constructors to types where a conversion truly makes sense. Everything else gets explicit.

Temporary objects and their short lives

A temporary is an unnamed object, destroyed at the end of the full expression that created it. That short life makes it a handy spot for validation.

Writing open_socket(Port{8080}) builds a temporary whose constructor runs the range check, so the rule lives in one place and every call site shares it. Validate once, at construction.

Operator overloading works best when your types behave like the ones your team already knows.

Keep each operator true to the type’s meaning, pick member or non-member by which side conversions should apply to, and let <=> handle comparisons on C++20 and later. Before C++20, you’ll write each comparison yourself.

In review, check for surprising implicit conversions, comparisons that disagree with ==, and copy assignments that skip self-assignment. Each is a small fix now and a large bug later.

Make your operators mean what readers expect, and your code won’t need a comment to explain it.

Questions

What is atoi() in C++?

`atoi()` is a C library function that converts the initial part of a null-terminated string to an `int`. It skips leading whitespace and accepts an optional sign, but it does not report conversion errors reliably; in C++, `std::stoi` is often a safer alternative when you need error handling.

What does to_string() do in C++?

`std::to_string()` converts a numeric value, such as an integer or floating-point number, into a `std::string` containing its decimal representation. It is declared in `<string>` and has overloads for several numeric types.

Read next

  1. Java vs C++: what differs in the code, and which to chooseCareers · Tobias Mwangi · written for C++23
  2. C++ operator overloading: signatures, member or friendLanguage · Miriam Castellanos · written for C++20
  3. How C++ Virtual Functions Pick the Right Code at RuntimeCareers · Tobias Mwangi