Operator Overloading
Lesson 19 of 20Teach + and << new tricks — overloaded operators make your own types read like the built-in ones.
Your types, natural syntax
Operators are just functions in disguise — and C++ lets you write the disguise for your own classes.
Operators are functions
a + b can secretly call a function you write named operator+. Same symbol, your meaning.
Member-friendly syntax
Once operator+ exists for Money, Money code reads like int code: total = bag1 + bag2.
Any sensible operator
Overload ==, <, + and more so sorting and comparing work naturally on your objects.
Rules apply
You cannot invent new operators or change precedence — and + should still feel like adding.
How a + b resolves
The compiler treats the plus sign as a function call — click through its search.
Teaching + to add Money
Press play — watch bag1 + bag2 turn into a real call to your operator+ function.
1#include <iostream>23class Money {4public:5int value;6Money(int v) {7value = v;8}9};1011Money operator+(Money a, Money b) {12Money sum(a.value + b.value);13return sum;14}1516int main() {17Money bag1(20);18Money bag2(15);19Money total = bag1 + bag2;20std::cout << "Total: " << total.value << "\n";21return 0;22}
The preprocessor pastes in iostream for cout.
Predict the output
operator+ can join words too — what does this program print?
1#include <iostream>2#include <string>34class Word {5public:6std::string text;7Word(std::string t) {8text = t;9}10};1112Word operator+(Word a, Word b) {13return Word(a.text + b.text);14}1516int main() {17Word w1("data");18Word w2("base");19Word w3 = w1 + w2;20std::cout << w3.text << "\n";21std::cout << w3.text.size() << "\n";22return 0;23}
Hint: operator+ joins the two strings: "data" + "base" becomes one word of 8 letters, and size() counts it.
Match the overloading terms
Click a term, then click its description to lock the pair.
Key takeaways
Operators are just functions with funny names: operator+ and friends.
Overloading makes your types read like int or std::string.
Keep overloaded meanings obvious — + should add, not surprise.
You cannot invent new operators or redefine &&, ::, . or ?:
Return a new value rather than quietly changing an operand.