Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does function overloading work in the following case?

Tags:

c++

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';
}
like image 294
Jeff Chen Avatar asked Jul 27 '26 06:07

Jeff Chen


1 Answers

As int& and int* are distinct types and i can be treated as a int& but not as a int*, 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.

like image 71
Alexander Gessler Avatar answered Jul 28 '26 19:07

Alexander Gessler