Skip to content

Operator Overloading

Beginning of the lesson

Operator Overloading

Teach the built-in operators how to work with your own types

Big Idea: In C++ an operator like +, == or << is really just a function with a symbolic name. When you write a class, you can supply your own version of that function so a + b, a == b or cout << a behave sensibly for your type — exactly as they do for int and string.
By the end of this topic you will be able to:
  • overload arithmetic and comparison operators (+, ==, <) for your own class,
  • choose correctly between a member operator and a free (non-member) operator,
  • overload operator<< for streams and use friend when private data is needed,
  • apply const-correctness and the right return types (value vs. reference),
  • recognise what you cannot do, and use the C++20 <=> shortcut.

1. An operator is a function in disguise

Think of the compiler as a translator. When it sees a + b, it does not have a hard-wired notion of "plus" for your class. Instead it looks for a function literally named operator+ that accepts operands of those types. If it finds one, it calls it; if it does not, the code fails to compile.

Analogy. The + symbol is like the word "combine". For numbers, "combine" means add. For strings it means join. For a shopping cart it might mean "merge two carts". The symbol stays the same, but you decide what combining means for your type — just as a single verb takes on different jobs in different contexts.

This is what makes user-defined types feel like first-class citizens. A Money, a Vector2D or a Matrix can be added, compared and printed with the same clean syntax as an int, instead of forcing readers to call a.add(b) everywhere.

a + b source you write member operator free operator a.operator+(b) left operand = this operator+(a, b) both operands = params Same result. The compiler chooses whichever overload you defined for these operand types.
The compiler rewrites a + b into a member call or a free-function call, depending on how you declared the operator.

Continue this lesson on YourAIZone

The full lesson has the complete explanation, worked examples, common mistakes, tests with instant checking and an AI tutor. Start right away as a guest, or create an account to keep your progress.

In the full lesson

  • The complete explanation
  • Worked examples
  • Common mistakes and how to avoid them
  • Test questions: 15
  • AI tutor that answers questions about the topic
  • Progress tracking for students, parents and teachers