Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function overloading in C++ [duplicate]

Tags:

c++

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)

like image 849
Belgi Avatar asked Nov 17 '11 20:11

Belgi


People also ask

What is function overloading in C?

Function overloading is a feature of a programming language that allows one to have many functions with same name but with different signatures. This feature is present in most of the Object Oriented Languages such as C++ and Java.

Why function overloading is not possible in C?

Function overloading is a feature of Object Oriented programming languages like Java and C++. As we know, C is not an Object Oriented programming language. Therefore, C does not support function overloading.

What is function overloading explain with example?

Function overloading is a C++ programming feature that allows us to have more than one function having same name but different parameter list, when I say parameter list, it means the data type and sequence of the parameters, for example the parameters list of a function myfuncn(int a, float b) is (int, float) which is ...

Does C allow overloaded functions?

And C doesn't support Function Overloading.


1 Answers

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.

like image 69
drdwilcox Avatar answered Sep 25 '22 15:09

drdwilcox