C++ Function Overloading

πŸ” C++ Function Overloading

Function overloading in C++ allows you to define multiple functions with the same name but with different parameter lists.
The compiler decides which function to call based on the number, type, or order of arguments.


πŸ”Ή 1. Why Use Function Overloading?

  • Improves code readability

  • Same logical operation, different inputs

  • Avoids unnecessary function names

  • Common in libraries and real-world code


πŸ”Ή 2. Basic Example

int add(int a, int b) {
return a + b;
}

double add(double a, double b) {
return a + b;
}

int main() {
cout << add(5, 10) << endl;
cout << add(2.5, 3.5);
}


πŸ”Ή 3. Overloading by Number of Parameters

int sum(int a, int b) {
return a + b;
}

int sum(int a, int b, int c) {
return a + b + c;
}


πŸ”Ή 4. Overloading by Parameter Types

void print(int x) {
cout << "Integer: " << x << endl;
}

void print(string x) {
cout << "String: " << x << endl;
}


πŸ”Ή 5. Overloading by Order of Parameters

void show(int a, double b) {
cout << "Int Double";
}

void show(double a, int b) {
cout << "Double Int";
}


πŸ”Ή 6. Function Overloading with Default Parameters ❌

void func(int a);
void func(int a, int b = 10);

❌ Ambiguous call:

func(5); // compiler error

πŸ”Ή 7. Function Overloading with References

void display(int &x);
void display(const int &x);

⚠️ Can cause ambiguity.


πŸ”Ή 8. Overloading with const

void show(int x);
void show(const int x); // ❌ NOT valid overloading

βœ” const on value parameter does not change signature.


πŸ”Ή 9. Overloading with Pointers

void print(int *x);
void print(double *x);

βœ” Valid (different types)


πŸ”Ή 10. What Is NOT Allowed in Function Overloading ❌

❌ Return Type Only

int func(int a);
double func(int a); // ❌ invalid

πŸ” How Compiler Resolves Overloading

  • Number of arguments

  • Data types

  • Exact match > type conversion

  • May fail if ambiguous


πŸ“Œ Summary

  • Same function name, different parameters

  • Return type alone cannot overload functions

  • Improves code clarity

  • Avoid ambiguous function calls

  • Common in OOP and libraries

You may also like...