It's seen that in the below code the constructor with parameter of type int
is being called. I know int
is fine here. But why not short
? as ASCII value of 'A'
gives 65 which a short
can accommodate.
On what criteria the constructor with the parameter of data type int
is invoked?
#include<iostream>
class RightData
{
int x;
public:
RightData(short data)
{
cout<< "Short" << endl;
}
RightData(int data)
{
cout<< "Int" << endl;
}
RightData(float data)
{
cout<< "Float" << endl;
}
~RightData()
{
cout<< "Final";
}
};
int main()
{
RightData *ptr = new RightData('A');
return 0;
}
The result of integral promotion is int
(not short
) for char
; and promotions (e.g. char
-> int
) have higher ranking than other conversions (e.g. char
-> short
) in overload resolution.
prvalues of small integral types (such as
char
) may be converted to prvalues of larger integral types (such asint
).
signed char
orsigned short
can be converted toint
;unsigned char
,char8_t
(since C++20) orunsigned short
can be converted toint
if it can hold its entire value range, andunsigned int
otherwise;char
can be converted toint
orunsigned int
depending on the underlying type:signed char
orunsigned char
(see above);
and (emphasis mine)
Note that all other conversions are not promotions; for example, overload resolution chooses
char
->int
(promotion) overchar
->short
(conversion).
The compiler always chooses the best matching overloading resolution.
in your case:
Type promotion is:
When casting implicitly, the compiler follows this ranking:
Since, char
to int
is integral promotion, it takes precedence over char
to short
which is conversion.
From here (emphasis mine):
char can be converted to int or unsigned int depending on the underlying type: signed char or unsigned char
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With