The following code compiles and runs but I’m not sure what exactly is going on at a lower level. Doesn’t a reference just store the address of the object being referenced? If so, both test functions are receiving an address as a parameter? Or is the C++ implementation able to differentiate between these types in some other way?
int main() {
int i = 1;
cout << test(i) << endl;
}
char test(int &i) {
return 'a';
}
char test(int *i) {
return 'b';
}
As
int&andint*are distinct types andican be treated as aint&but not as aint*, overload resolution is absolutely unambiguous here.It doesn’t matter at this point that references are just a somewhat cloaked kind of pointer. From a language point of view they are distinct types.