The short difference
Function overloading gives several functions the same name, and the arguments decide which one runs. Operator overloading gives operators such as + or << a meaning for your own types. The two are related: an overloaded operator is a function whose name is operator followed by the symbol.
Both are types of overloading, which is covered in what is overloading and its types. Operator overloading in C++ is the part most people mean when they compare the two.
Function overloading in practice
int area(int width, int height) {
return width * height;
}
double area(double radius) {
return 3.14159 * radius * radius;
}
Both functions are named area. A call such as area(3, 4) uses the first version, and area(2.0) uses the second. For the full set of rules, see what is function overloading.
Operator overloading in practice
struct Vec2 {
double x;
double y;
};
Vec2 operator+(const Vec2& a, const Vec2& b) {
return Vec2{a.x + b.x, a.y + b.y};
}
int main() {
Vec2 first{1.0, 2.0};
Vec2 second{3.0, 4.0};
Vec2 sum = first + second; // calls operator+(first, second)
}
Here + is defined for Vec2. The expression first + second is a shorter way of calling that function, and sum ends up with x equal to 4.0 and y equal to 6.0.
Key differences
| Function overloading | Operator overloading | |
|---|---|---|
| What shares a name | Functions | Operator symbols |
| How code calls it | area(3, 4) |
first + second |
| Can you create new symbols? | Not applicable | No, you can only overload existing operators |
| Precedence and associativity | Not applicable | Stay the same as the built-in operator |
| Main purpose | The same action for different inputs | Natural syntax for your own types |
Rules that only apply to operators
- You can’t overload
::,.,.*,?:,sizeof, ortypeid. - You can’t change an operator’s precedence or associativity.
- You can’t make an operator take a different number of operands than its built-in form allows.
- Overloaded operators should behave the way readers expect. A
+that adds twoVec2values is clear. A+that does something unrelated is not.
When to use each
- Use function overloading when the same job applies to different inputs, such as printing an
intor adouble. - Use operator overloading when a type represents a value that naturally supports the operator, such as a vector, a fraction, or an amount of money.
- If neither fits, use a clearly named function instead.
Key takeaways
- Both features reuse a name, and the compiler chooses the version at compile time.
- Function overloading works with any function name. Operator overloading works only with existing operators.
- Operator overloading is a special case of function overloading, because each overloaded operator is a function.