C++ Function Overloading – One Name, Many Jobs
Function overloading allows you to use the same function name for different tasks, as long as the number or types of parameters differ.
It’s like having multiple versions of a function—same name, but different signatures. 📦🔄
🎯 Why Use Overloading?
It makes code cleaner, readable, and allows function names to be reused without confusion.
🧪 Example: Add Function Overloaded
We’ll write an add
function that works with both integers and floating-point numbers.
#include <iostream> using namespace std; int add(int a, int b) { return a + b; } float add(float a, float b) { return a + b; } int main() { cout << "Int sum: " << add(5, 10) << endl; cout << "Float sum: " << add(2.5f, 3.5f) << endl; return 0; }
📘 Rules for Overloading
- Functions must differ by the number or type of parameters.
- Return type alone is not enough to overload a function.
🧪 Invalid Example: Overloading by Return Type Only
This won’t work and will cause a compiler error:
// ❌ This will NOT compile int display(int x) { return x; } float display(int x) { return (float)x; }
✅ Summary
- Function overloading means using the same name for functions with different parameter lists.
- Improves readability and reduces redundant naming.
- Cannot overload solely by return type.
With function overloading, you can make your programs more flexible and your function names way cooler 😎