Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does constructor choose type INT instead of SHORT when invoked with a parameter of type CHAR?

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; 
}
like image 692
Abhinav Kinagi Avatar asked Jul 24 '19 08:07

Abhinav Kinagi


3 Answers

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 as int).

  • signed char or signed short can be converted to int;
  • unsigned char, char8_t (since C++20) or unsigned short can be converted to int if it can hold its entire value range, and unsigned int otherwise;
  • char can be converted to int or unsigned int depending on the underlying type: signed char or unsigned char (see above);

and (emphasis mine)

Note that all other conversions are not promotions; for example, overload resolution chooses char -> int (promotion) over char -> short (conversion).

like image 155
songyuanyao Avatar answered Oct 12 '22 06:10

songyuanyao


The compiler always chooses the best matching overloading resolution.

in your case:

Type promotion is:

  1. A char, unsigned char or short can be promoted to an int. For example void f(int); can be a match for f('a');
  2. A float can be promoted to a double.
  3. A bool can be promoted to an int (FALSE counts as 0, TRUE as 1).
like image 4
nivpeled Avatar answered Oct 12 '22 05:10

nivpeled


When casting implicitly, the compiler follows this ranking:

  1. Exact match
  2. Promotion
  3. Conversion

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

like image 4
CinCout Avatar answered Oct 12 '22 06:10

CinCout