Skip to main content

Command Palette

Search for a command to run...

function Overloading

Updated
•2 min read•View as Markdown

🧩 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 CallWhich Function RunsWhy
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 changeExample
Number of argumentssum(int, int) and sum(int, int, int)
Type of argumentssum(int, int) and sum(float, float)
Order of argumentssum(int, float) and sum(float, int)

More from this blog

Amit singh's blog

235 posts