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.
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);
}5 4The 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.
