Consider the following code:
enum ABC : char
{
a, b, c
};
void ff(char c)
{
cout << "char\n";
}
void ff(int i)
{
cout << "int\n";
}
int main()
{
ff(a); // char
}
May I ask why complier matches ff(char)
instead of ff(int)
?
I came up with this question when I was reading C++ Primer (5th Edition). On page 835, the writers state:
... we can pass an object or enumerator of an unscoped enumeration to a parameter of integral type. When we do so, the
enum
value promotes toint
or to a larger integral type ... Regardless of its underlying type, objects and the enumerators ... are promoted toint
.
My understanding to the above quote is that, when being passed to a function expecting an integral argument, an enumerator will first be casted "at least" into an int
. So, I'm expecting the above code to call ff(int)
. Actually, even my Visual Studio editor is showing that: (Sorry I know that we should avoid having screenshot here but I just want to show what I saw)

I also noticed that if I don't explicitly specify the underlying type for ABC
, then ff(int)
will be called.
So my current guess goes like this: If we don't explicitly specify the underlying type, then the object/enumerator passed to the integral parameter will first be casted into an int
. But if the underlying type is explicitly specified, then the compiler will first try to match the overloaded function which expects the specified type.
May I ask if my guess is correct?
Because an enum with fixed underlying type can implicitly convert to its underlying type. The underlying type is
char
and thus the conversion tochar
is the most preferred candidate overload.A cast is an explicit conversion. The conversion in this example is implicit.
The exact preferred conversion depends on the values of the enum. The language rule is a bit complex, so I'll copy it verbatim from the standard:
In this case,
int
is a correct guess because it is the first type in the list of the quoted standard rule, and it can represent all values of the enum which are 0, 1 2. But the guess does not apply universally.