Function Overloading in C++
In this lesson: Same function name, different parameters — function overloading rules in C++ with examples and output. In Hindi & English.
What is function overloading?
Function overloading lets you give several functions the same name, as long as their parameter lists differ — a different number of parameters, or different types. C++ figures out which one you meant from the arguments you pass.
Why overload?
Without overloading you would need clumsy names for the same idea: addInts, addDoubles, addThree. Overloading lets one clear name — add — serve them all, so callers do not have to remember variants.
A working example
#include <iostream>
using namespace std;
int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; }
int add(int a, int b, int c) { return a + b + c; }
int main() {
cout << add(2, 3) << "\n"; // int version
cout << add(2.5, 3.5) << "\n"; // double version
cout << add(1, 2, 3) << "\n"; // three-arg version
return 0;
}5
6
6
How the compiler chooses
The compiler matches your call to the version whose parameters best fit the argument types and count — a process called overload resolution. In the example, add(2, 3) matches the two-int version, add(2.5, 3.5) matches the two-double version, and so on.
What counts as different
| Difference | Valid overload? |
|---|---|
| Different number of parameters | Yes |
| Different parameter types | Yes |
| Different order of types | Yes (e.g. (int,double) vs (double,int)) |
| Only different return type | No — not allowed |
| Only different parameter names | No — names do not count |
Common mistakes
- Trying to overload by return type only — not allowed.
- Writing two versions that are ambiguous, so no single best match exists.
- Thinking different parameter names make an overload — only types/count matter.
- Confusing overloading (compile-time) with overriding (run-time, via virtual functions).
Write an overloaded area function: one for a square (one side), one for a rectangle (length and width), and one for a circle (radius, returning a double). Call each from main.
Summary
- Overloading = several functions with the same name, different parameters.
- The compiler picks the version that best matches your arguments.
- Overloads must differ in parameter count, types or order.
- You cannot overload by return type or parameter names alone.
- Overloading is compile-time; overriding is a separate run-time concept.
Frequently Asked Questions
What is function overloading in C++?
Why is function overloading useful?
addInt, addDouble and addThree. This makes code cleaner and easier to read, since add(...) works whether you pass two ints, two doubles or three numbers.