Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does passing the literal 3 choose the int overload instead of the short overload?

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?

like image 604
Gaurav Avatar asked Aug 08 '17 09:08

Gaurav


3 Answers

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.

like image 112
StoryTeller - Unslander Monica Avatar answered Oct 26 '22 04:10

StoryTeller - Unslander Monica


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.

like image 33
kocica Avatar answered Oct 26 '22 04:10

kocica


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

like image 17
doctorlove Avatar answered Oct 26 '22 04:10

doctorlove