How does C++ handle function overloading in this case?
#include <iostream>
void func(int x)
{
std::cout << "integer";
}
void func(short x)
{
std::cout << "short";
}
int main(void)
{
func(3);
}
Output: integer
Why is that?
Constants have types too. And without a suffix to indicate otherwise, 3
is simply an int
constant. The compiler will choose a larger type if the constant is too big, but it won't go for things smaller than an int
by default.
Now, it just so happens, that there is no suffix to make a short constant. You'd need to add a cast if you want that particular overload to be called.
operator ""
it seems like, neat en.cppreference.com/w/cpp/language/user_literal
Commented
Aug 9, 2017 at 7:27
Literal 3
is a constant and implicitly is of type int
by the language design.
For your short
overloaded function execution you have to use short
variable:
short s = 3;
fun(s);
or cast the constant properly:
fun((short)3);
fun(static_cast<short>(3));
Type short
hasn't suffix like for example long
(long l = 42L;
), but you can create one.
Because 3
is an integer.
fun(static_cast<short>(3));
would call the short version.
Or you can use user-defined literals to make a short: See here
You are doing
fun(3);
and 3 is a literal constant integer so the function that better matches the overload is this one
void fun(int x)
{
std::cout << "integer";
}
feel free to play a litte with the types and casting those like:
fun(short(3));
fun(int(3));
// C++11
auto x = 3;
fun(x);
The constant 3
has it's own type, in this case it's an int
. You need to explicitly cast your constant to short
if you want your overload to execute
fun((short)3);
3
is integer.short
type. As it got ported to new architectures and standardized, C kept the assumption thatint
is the native word length, and the most convenient default size to work with. This is also the reason forchar
and other types narrower thanint
getting automatically converted toint
in some situations: this is faster on many machines, including the PDP.int, long, long long
. The inconsistency is thatshort
is missing from that list.typeid(3).name()
(you must#include <typeinfo>
for this to work. The result would bei
in this case. If you cast it toshort
, you'd sees
instead.