4

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;
}
banarni
  • 113
  • 4

2 Answers2

4

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.

Barry
  • 286,269
  • 29
  • 621
  • 977
2

Promotions and conversions create a new temporary object. Non-const references cannot bind to temporaries.

Oktalist
  • 14,336
  • 3
  • 43
  • 63
Revolver_Ocelot
  • 8,609
  • 3
  • 30
  • 48