underneath, passing by reference involves passing the pointer to the thing being referenced; maybe this will give some insights into how it works
so in the example from above,
void foo( int val ) {
val = 1;
}
void foo2( int &ref ) {
ref = 1;
}
int main( void ) {
int num = 2;
foo( num ); std::cout << num << "\n";
foo2(num ); std::cout<< num << "\n";
return 0;
}
is equivalent to this in C:
void foo( int val ) {
val = 1;
}
void foo2( int *ref ) {
*ref = 1;
}
int main( void ) {
int num = 2;
foo( num ); printf("%d\n", num);
foo2(&num ); printf("%d\n", num);
return 0;
}
notice how the reference declaration is equivalent to a pointer declaration, except that every time you use the reference, it is dereferenced automatically without you having to use * explicitly like with a pointer; and whenever you call a method with a reference argument, or assign to a reference, you take the address of the variable, without explicitly using & like with a pointer
also note that in the C++ code above, this won't work:
because the reference needs to have an addressable expression to point to