function Overloading
🧩 What is Function Overloading?
👉 Function overloading means same function name, but different parameters.
C++ decides which function to run based on the arguments you give when calling it.
So, you can write one function name like add() that works for:
adding integers
adding floats
adding 3 numbers, etc.
🧠 Why use it?
Because we can use one function name for similar tasks — instead of creating many names like addInt(), addFloat(), etc.
It makes code clean and readable.
💻 Example: Easy one
#include <iostream>
using namespace std;
// 1️⃣ Add two integers
int add(int a, int b) {
return a + b;
}
// 2️⃣ Add three integers
int add(int a, int b, int c) {
return a + b + c;
}
// 3️⃣ Add two floats
float add(float a, float b) {
return a + b;
}
int main() {
cout << "Add 2 ints: " << add(5, 10) << endl;
cout << "Add 3 ints: " << add(2, 3, 4) << endl;
cout << "Add 2 floats: " << add(2.5f, 3.5f) << endl;
}
🧾 Output
Add 2 ints: 15
Add 3 ints: 9
Add 2 floats: 6
🔍 How it Works (Step by Step)
| Function Call | Which Function Runs | Why |
add(5, 10) | int add(int, int) | 2 integer arguments |
add(2, 3, 4) | int add(int, int, int) | 3 integer arguments |
add(2.5f, 3.5f) | float add(float, float) | 2 float arguments |
👉 C++ looks at number and type of parameters to decide which one to call.
⚠️ Important Rule
You can’t overload a function by changing only the return type.
❌ Wrong Example:
int test(int a);
float test(int a); // Error! Only return type is different
Compiler gets confused because parameters are same.
✅ Valid Overloading Changes
| Works if you change | Example |
| Number of arguments | sum(int, int) and sum(int, int, int) |
| Type of arguments | sum(int, int) and sum(float, float) |
| Order of arguments | sum(int, float) and sum(float, int) |