Function overloading
In the previous chapter, when we discussed inheritance, we mentioned static binding. We saw that we can have the same function names for functions that belong to different classes. However, we can also have the same function names for different function parameters, as shown in the following example:
#include <cstdio>
void print(int a) {
printf("Int %d\r\n", a);
}
void print(float a) {
printf("Float %2.f\r\n", a);
}
int main() {
print(2);
print(2.f);
return 0;
}
In this example, we have two print
functions. One of them has an int
as a parameter and the second one has a float
. On the call site, the compiler will pick a print
function based on the arguments passed to the function call.
Functions with the same names within the same scope are called overloaded functions. Instead of having two different names, such as print_int
and print_float
, we can use the same name for both these functions and let the compiler...