Operator overloading is a C++ feature that lets you define what an operator, such as +, does when its operands are your own types. A class for money can define + so that adding two amounts looks the same as adding two numbers.
The basic idea
Built-in types such as int and double already know what + means. A type you create doesn’t. If you write a + b on two of your objects without defining anything, the compiler reports an error. To fix that, you write a function named operator+ in your class. When the compiler sees a + b and a is your type, it calls that function.
Example: adding money amounts
The Money class below stores an amount in whole cents, so the addition is exact integer math.
#include <iostream>
class Money {
public:
explicit Money(int cents) : cents_(cents) {}
Money operator+(const Money& other) const {
return Money(cents_ + other.cents_);
}
int cents() const { return cents_; }
private:
int cents_;
};
int main() {
Money a(250); // $2.50
Money b(199); // $1.99
Money total = a + b; // calls a.operator+(b)
std::cout << total.cents() << " cents\n";
}
Output:
449 cents
Here is what happens:
operator+is a member function, soa + bis the same asa.operator+(b).- It returns a new
Moneyobject and leavesaandbunchanged. - The constructor is marked
explicit, so a plain integer doesn’t turn into aMoneyby accident. A line likeMoney m = 250;won’t compile.
Why it’s useful
Once + works, the code reads the way you would write the sum on paper: total = a + b. Without overloading, you would write total = add(a, b). Both work, but the operator form is shorter and closer to the math it describes.
Things to keep in mind
- The operator should do what a reader expects.
+should add, not subtract. - Not every operator can be overloaded. Which operators cannot be overloaded is a short, fixed list that includes
::and.. - At least one operand must be your type or an enumeration, so you can’t redefine how
int + intworks.
In short
Operator overloading lets your class use operators like + by defining a function named operator+. The compiler calls that function whenever it sees the operator used with your type.