Search code examples
c++type-conversionpass-by-referenceoverloadinginteger-promotion

Pass-by-reference and integral promotion


Why isn't the compiler able to promote char to int& but has no problem when passing it by reference-to-const (char to int const&)?

Example code:

#include <iostream>
using namespace std;

void func1(int & i)       { cout << "int &       " << i << endl; }
void func2(int const & i) { cout << "const int & " << i << endl; }

int main() {

    char mychar = 'a';
    func1(mychar);    // compiler-error
    func2(mychar);    // no error

    return 0;
}

Solution

  • This is allowed:

    char c = 'X';
    const int& i = c;
    

    We're implicitly promoting c to int and binding i to that temporary. This can't really lead to any confusing behavior. i has the same value c did, it's just a different type.

    But what would happen if the same logic were allowed with non-const:

    char c = 'X';
    int& i = c;
    i = 'J';
    

    i can't bind directly to c - it's the wrong type. We'd still need to promote c to and int and bind i to that temporary. But when we assign i, we're just modifying that temporary we bound - c would still be X. That would be incredibly confusing, non-intuitive, and error-prone. So the language forbids it.