An overloaded function is a function with the same name but different parameters. When calling an overloaded function, the compiler must determine which version of the function to execute based on the types and number of arguments being passed to the function. If the compiler cannot determine which version of the function to execute based on the arguments being passed, it is said to be ambiguous and will result in a compile-time error.
For example, consider the following code:
void print(int x) {
std::cout << "int: " << x << std::endl;
}
void print(double x) {
std::cout << "double: " << x << std::endl;
}
int main() {
print(1); // calls print(int)
print(1.0); // calls print(double)
print(1.0f); // error: ambiguous call
}
In this example, the call to print(1.0f) is ambiguous because the compiler cannot determine whether to call print(int) or print(double) based on the argument being passed. To fix this error, you can either explicitly cast the float to int or double, or you can define a separate version of the print function that takes a float as an argument.
Here are a few more things to consider when it comes to overloaded functions:
- Overloaded functions must have different parameter lists, which means that they can differ in the number of parameters, the types of the parameters, or both.
- It's possible to have multiple overloaded functions that have the same number of parameters but differ in the types of the parameters. For example:
- Overloaded functions must have different parameter lists, which means that they can differ in the number of parameters, the types of the parameters, or both.
- It's possible to have multiple overloaded functions that have the same number of parameters but differ in the types of the parameters.
For example:
void print(int x) {
std::cout << "int: " << x << std::endl;
}
void print(double x) {
std::cout << "double: " << x << std::endl;
}
int main() {
print(1); // calls print(int)
print(1.0); // calls print(double)
print(1.0f); // calls print(double)
}
In this example, the call to print(1.0f) is not ambiguous because the compiler can determine that the float should be converted to a double and the print(double) function should be called.
It's also possible to have multiple overloaded functions that have different numbers of parameters, as long as the types of the parameters are distinct.
For example:
void print(int x) {
std::cout << "int: " << x << std::endl;
}
void print(int x, int y) {
std::cout << "int, int: " << x << ", " << y << std::endl;
}
void print(double x) {
std::cout << "double: " << x << std::endl;
}
int main() {
print(1); // calls print(int)
print(1, 2); // calls print(int, int)
print(1.0); // calls print(double)
}
In this example, the calls to print(1) and print(1, 2) are not ambiguous because the compiler can determine which version of the function to call based on the number of arguments being passed.
I hope this helps! Let me know if you have any questions.

