Nicholas White
Nicholas White

Reputation: 2722

Do parameter or return type implicit conversions take priority in C++?

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?

Upvotes: 2

Views: 339

Answers (2)

MSalters
MSalters

Reputation: 179877

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;

Upvotes: 3

Mark Ransom
Mark Ransom

Reputation: 308206

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

Upvotes: 8

Related Questions