6

Possible Duplicate:
List of C++ name resolution (and overloading) rules

What are the rules in C++ for how the compiler decides which function to choose ? (that's is given two functions with the same name - how does the compiler pick/prioritize one function over the other, mainly I want to know what types of casting the compiler is more willing to do when he chooses)

Community
  • 1
  • 1
Belgi
  • 14,542
  • 22
  • 58
  • 68

3 Answers3

4

As already stated, the rules are fully described in the standard. As a basic rule of thumb, the compiler will select the overload that requires the least automatic conversions, with the caveat that it will never apply 2 user-defined conversions.

Integer types get automatically cast around a lot. So if you have a function overloaded on an int and a double, the compile will pick the int function if called with a constant that is an integer. If you didn't have the int version, the compiler would select the double one. And among various integer types, the compiler prefers int for integer constants, because that is their type. If you overloaded on short and unsigned short, but called with a constant of 5, the compiler would complain that it couldn't figure out which overload to use.

Scott Meyers' book does indeed have the best explanation I have ever read.

drdwilcox
  • 3,833
  • 17
  • 19
0

The entire function name is comprised of what you called the function as well as the parameter list. So, logically, 2 functions called the same thing but with different parameter lists both have different "full names." My terminology is probably a bit off, so if someone wants to correct that, feel free.

MGZero
  • 5,812
  • 5
  • 29
  • 46
  • 1
    say you have doSomething(int x) and doSomething(short x), which does the compiler choose when you call doSomething(5) ? – Tom Nov 17 '11 at 20:08
  • Ahh, that makes it more interesting! Good question, and also beyond the scope of my knowledge. I feel like it would depend on what the compiler considers 5 to be. I'm inclined to say int, but I'm not certain at all. – MGZero Nov 17 '11 at 20:09
  • 1
    It will choose the `int` version. – drdwilcox Nov 17 '11 at 20:09
0

It is based on the type of the argument(s). No casting involved if the type does not match it simply will not compile.

Miguel Garcia
  • 1,029
  • 5
  • 14