MM> Whenever I want to pass something by reference I do it
MM> manually (as follows):
MM> void afunction(int *var1)
MM> {
MM> *var1=546;
MM> }
MM> void main()
MM> {
MM> int k;
MM> afunction(&k);
MM> }
This isn't passing by reference, per se. It's passing a pointer to an
object. The difference is, as you say, "manual." Reference passing in every
language is an automatic thing handled by the compiler. For example, many
people coming from a pascal background would recognize:
procedure foo(var integer: by_ref; integer: by_val; integer^: by_ptr);
A special keyword (var) allows you to pass the item by reference where the
compiler will handle the "link" between the by_ref variable in the procedure
and the parameter that was originally passed in.
C++'s special keyword is the &. :-)
void foo(int& by_ref, int by_val, int* by_ptr);
Note that by_ptr is _still_ a method of passing _by value_. You are passing
the _value_ of the pointer itself, which, indirectly, can be used (with the *
[dereference] operator) as a reference.
MM> - this works out logically as far as I can tell. As in
MM> the declaration says that '*var1' is an integer, and so
MM> 'var1' by itself is a pointer to the integer. Then I
Right - by_ptr would be, by itself a "int *" or a pointer to int. by_val
would be a "int" or just an int. And by_val would be "int&" or _reference_
to int.
MM> ie. An integer variable can just be passed to it
MM> ordinarily. This is really confusing me. :-) I hate
MM> trying to work out where pointers are going and stuff
MM> but by my logic so far, '&var1' would be an integer and
Actually, the interesting thing is how &var1 would work.
#include
void foo(int& k)
{
cout << "in foo, &k = " << (void*)&k << endl;
}
int main()
{
int main_k;
cout << "in main, &main_k = " << (void*)&main_k << endl;
foo(main_k);
return 0;
}
The output would show something very interesting. &k will be identical to
&main_k! They both automagically have the same pointer. Thinking of k as
just "an int", you can see how k can have its address taken... but as a
reference, its address will be the same as the object it refers to, in this
case, main_k.
MM> Is it just me who's having a hell of a time thinking
MM> this through or is this some sort of exception in the
MM> design of the language whereby a '&' character can be
MM> used to get the compiler to automagically work out all
MM> the pointer stuff? :-]
In variable declaration, & makes the variable a _reference_ to a type. This
is not completely unlike the miriad of meanings some of the other symbols
have... such as static, * (multiply, dereference, declare a pointer), ...
Hope this helps,
---
---------------
* Origin: Tanktalus' Tower BBS (1:250/102)
|