Function overloading
- C++ course
- Beginner
- Lesson 68/116
- 5 min
Learn to define same-named functions with different parameters.
Function overloading
C++ lets several functions share one name; this is overloading. The requirement is that the parameter lists differ. int add(int a, int b) and double add(double a, double b) share the name but have different signatures.
The compiler picks the right version by looking at the argument types at the call; this mechanism is called overload resolution. add(2, 3) calls the int version, add(2.5, 3.5) calls the double version. You just write add.
Return type is not part of the signature
If two functions differ only by return type, it is not overloading; you get a compile error. int f() and double f() share a signature because their parameter lists match.
The reason is that a call uses only the name and arguments; the caller does not have to know the return type in advance. To separate two versions you must change the parameter types or count. For instance int f(int x) and double f(double x) form a valid overload pair.
Practice Write two add overloads
Define two add functions: int add(int a, int b) returning an integer, and double add(double a, double b) returning a decimal. In main, print the results of add(2, 3) and add(2.5, 3.5) separated by a space.
Starter code
#include <iostream>
// Define int add overload
// Define double add overload
int main() {
// Print both add calls
return 0;
}Sample solution
#include <iostream>
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
int main() {
std::cout << add(2, 3) << " " << add(2.5, 3.5) << std::endl;
return 0;
}Expected output
5 6
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the overload definition
double add(double a, ____) { return a + b; }
double add(double a, double b) { return a + b; }
Explanation: double add(double a, double b) is a signature separate from the int version.
2 Match overload resolution
| Term | Meaning |
|---|---|
add(2, 3) |
int version |
add(2.5, 3.5) |
double version |
different parameters |
Overload requirement |
compiler picks |
Resolution |
3 Which two functions form a valid overload pair?
// ???- int f(int x) and int f(double x) Correct answer
- int f(int x) and int f(int x)
- void f() and void f()
- int f() and double f()
Explanation: same name with different parameter types is valid overloading.