Function Overloading
Say you want a function that doubles a number, and another one that repeats a piece of text two times. Both do the same kind of job, so it would be nice to give them the same name. C++ lets you do that. Several functions can share one name, as long as their parameters are different. This is called function overloading.
#include <iostream>
#include <string>
using namespace std;
int twice(int n) {
return n * 2;
}
double twice(double n) {
return n * 2;
}
string twice(string text) {
return text + text;
}
int main() {
cout << twice(21) << "\n";
cout << twice(1.25) << "\n";
cout << twice("ha") << "\n";
return 0;
}
Output:
42
2.5
haha
These are three separate functions, and all of them are called twice. At each call, the compiler looks at the type of the argument and picks the version whose parameter matches:
21is anint, so the first version runs.1.25is adouble, so the second version runs."ha"is text, so thestringversion runs. For strings,+joins the two pieces, so you gethaha.
The compiler makes this choice when it compiles your program, not while the program runs.
You have used overloading since your first program. cout << can print an int, a double or a string because the C++ library has a separate version of << for each type.
The parameters must be different
Two versions with the same name must differ in their parameters: a different number of parameters, or different types. A different return type alone is not enough:
#include <iostream>
using namespace std;
int getValue() {
return 1;
}
double getValue() {
return 1.5;
}
int main() {
cout << getValue() << "\n";
return 0;
}
Output:
main.cpp:8:8: error: ambiguating new declaration of ‘double getValue()’
The error points at line 8, the second getValue. It clashes with the first one, because both take no arguments. At a call like getValue(), the compiler would have no way to know which one you mean, so it does not allow the second one.
Use overloading only when all the versions do the same job for different types, like twice above. If each version did something different, the code that calls them would be hard to understand.
In the exercise, an add function for two int values is ready. Write two more versions of add: one for two double values, and one that joins two strings.