Say you have
void foo(int a, int &b, int *c){...}
int main(){
int d=0, e=1, f=2;
foo(d, e, &f);
}
It is my understanding that the function declaration parameters must have the same type as the argument. Hence the "int" in front of a, b, and c because d, e, and f are all ints.
But does this extend (also apply) to the references and pointers, i.e. &
and *
?
What I mean is, if you have int &b
, does e
have to be an address already?
I thought it did, but now I think I have the concept wrong after reading this thread: C++ functions: ampersand vs asterisk in which the code outlined in is pretty much what I have written above.
After reading the thread and the code above, it seems that the &
and *
in the parameter is actually not part of the "type restriction" -- i.e. it does not mean that e has to be an address, or that f has to be a pointer.
See previously I thought that whatever proceeded the paramater names a, b, c
in the parameter was strictly specifying what type it must be
so you would code something like this:
void foo(int a, int &b, int *c){...}
int main(){
int d=0, e=1, f=2;
foo(d, &e, *f); // wrong
}
Instead, it seems that the &
in the parameter actually takes the variabe/object argument that is passed in and CHANGES or GETS its address. And the *
is actually ACTING UPON the address of f (&f
) which is passed as an argument and retrieving it's contents. Is this right?
Is this just the given protocol/rule for &
and *
placed in the parameter that one must accept?
I've read up on many articles regarding references and pointers in parameters, and they all explain very clearly that the &
and *
in the parameter allows one to change the value of the variable passed. However, they never go very deep into the actual procedure/protocol of the &
and *
when placed in the parameter.
http://www.cplusplus.com/doc/tutorial/functions2/
http://www.learncpp.com/cpp-tutorial/73-passing-arguments-by-reference/
Let me know if I have this conceptually right. Thank you!