In function overloading, compiler has to find which overloaded function to invoke for function call. Determining the right function to invoke is called overload resolution. Differentiation in overloading is one part and resolution is to the right function is rest of the part.
Compiler applies a sequence of rules on the function calls where it does promotions/conversions to the argument(s) and with each conversion, it checks if there is an exact match or not. There are three possible ways it ends:
- An exact match found, great!
- No match found, compilation error.
- More than one match found, ambiguous resolution and so compilation error.
The order of applying this rule is:
- Step 1: Finding exact match by arguments. If required, applying trivial conversions such as conversion to
constetc.
For example,
void print(const int value)
{
cout<<value;
}
int a {1};
print(a); // int a converted to const- Step 2: If step 1 does not work, compiler applies numerical promotions.
For example,
void print(int value)
{
cout << value;
}
void print(double value)
{
cout << value;
}
print('a'); // promoted to int
print(1.3f) // promoted to double- Step 3: Compiler applies numeric conversions if promotions do not work.
For example,
void print(double value)
{
cout << value;
}
void print(std::string value)
{
cout << value;
}
print(1); // converted to double- Step 4: If numeric conversions also do not work, compiler checks if conversion can be applied using user defined conversions.
Ambiguous Matches
When compiler finds more than one matches for the overloaded function call it throw compilation error. An example of ambiguous matches is shown below.
void print(double value)
{
cout << value;
}
void print(char value)
{
cout << value;
}
print(1); // int can be converted to both char and doubleint can be converted to both char and double so it is ambiguous match and compilation gives error.