Reputation: 405
i have a problem with function overloading while using const function and const object. Can someone explain why "const foo int& int" is being print instead of "foo int char&" in the following code?
struct A
{
void foo(int i, char& c) { cout << "foo int char&" << endl;}
void foo(int& i, int j) const { cout << "const foo int& int" << endl;}
};
int main() {
A a;
const A const_a;
int i = 1;
char c = 'a';
a.foo(i,i);
}
Thanks,
Upvotes: 0
Views: 990
Reputation: 310920
There is all clear. You called a function with two arguments of type int. There are two function candidates. One that have the first parameter of type int and the second parameter of reference to char. So to call this function the second argument shall be implicitly converted to type char &. But it is a narrowing conversion because the rank of int is higher than rank of char. So a temporary object will be created but temporary object may only be binded with a const reference. The second function does not require any conversion of its arguments. So it will be called.
Upvotes: 2
Reputation: 208323
The first function cannot be called with an int as the second argument. A char&
cannot be bound to an int
. That means that only the second overload is an alternative.
Upvotes: 1
Reputation: 2898
Upvotes: 0
Reputation: 3569
Cause void foo(int& i, int j)
const is a better match, other function needs an int to char convertion.
Upvotes: 1