Why the compiler can overload functions with passing by reference and passing by value
c++, function, overloading, reference
Solution
Broadly speaking functions can be overloaded on the basis of:
- Number of arguments
- Type of arguments
- Sequence of arguments
The example compiles because it satisfy's the second criteria. `int` and `int &` are different data types.
Consider the following example:
void foo(int i);
void foo(int& i);
void foo(int i){}
void foo(int& i){}
int main()
{
return 0;
}
The above code compiles because it is valid code. Depending on what function argument is passed to the function the compiler may/may not detect the best match for the function call. So the functions themselves are allowed to co-exist but their usage in certain ways may cause ambiguity for the compiler.
For example: In the following code, a literal cannot be bound to a non-const reference and hence the only candidate for function call is the non reference version and this should compile and work just fine:
void foo(int i);
void foo(int& i);
void foo(int i){}
void foo(int& i){}
int main()
{
foo(20);
return 0;
}
But,
void foo(int i);
void foo(int& i);
void foo(int i){}
void foo(int& i){}
int main()
{
int i = 10;
foo(i);
return 0;
}
the above will cause ambiguity for the compiler because compiler cannot detect the best match between the two function calls.
Problem
I thought that during overloading, compiler checks whether the formal arguments are of the same type. For example: ``` void a(int x) void a(double x) ``` can overload simply because the two "x"s have the difference type. However, does the following two have the different type? ``` void f(int y) void f(int& y) ``` I understand that one is PBV and the other PBR. But the second y has the type "int" as well right? Why it compiles successfully? P.S. I notice that although it compiles, it does not run though, reporting run-time error of ambiguity.