views:

173

answers:

2

If I have the code:

int f(int a) { return a; }
double f(double g) { return g; }

int main()
{
    int which = f(1.0f);
}

Which overload of f is called, and why?

+7  A: 

The return type is not considered for overload purposes at all, thus you'll get the double version.

Mark Ransom
+3  A: 

To understand why it's this way, consider this call:

int bar = f(g(h(foo)));

As overload resolution involves only arguments, you can deduce h, then g and finally f, independently. If the return value was involved, you'd need to deduce them concurrently. If each has 10 overloads, in the first case you're checking 30 possible overloads and in the second case 1000 possible combinations. And if you think such nested code is rare, consider

std::cout << "int i = " << i << std::endl;
MSalters