Search code examples
c++c++11typesconstructoroverload-resolution

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; 
}

Solution

  • 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).