C++ ยท Chapter 28 of 49

C++ Function Overloading

Function overloading lets you define multiple functions with the same name but different parameter lists (different types or counts). The compiler picks the correct version based on the arguments used at the call site.

Overloading improves readability by letting related operations share one intuitive name instead of needing addInt, addDouble, and so on.

How overloading works

The compiler distinguishes overloads by parameter types and count (not return type alone). Calling `add(2, 3)` vs `add(2.5, 3.5)` picks a different overload automatically.

Operator overloading (preview)

C++ also allows overloading operators like `+` or `==` for custom classes, so objects can be combined or compared with natural syntax โ€” covered later with classes.

Example 1 (cpp)
int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; }
int main() {
    std::cout << add(2, 3) << " " << add(2.5, 1.5);
}
Output
5 4

The compiler picks the int or double version based on argument types.

Key points

  • Overloaded functions share a name but differ in parameters.
  • The compiler resolves calls based on argument types/count.
  • Return type alone cannot distinguish overloads.
  • Operators can also be overloaded for custom types.
๐Ÿ’ก Note: Ambiguous overloads (e.g. calling with a type convertible to two options equally) cause a compile error.

๐Ÿ“ Quick Quiz

1. Overloaded functions must differ in:

2. Who decides which overload to call?

3. Can return type alone distinguish two overloads?