TIP: Click on subject to list as thread! ANSI
echo: c_plusplus
to: MICHAEL MCGAVIN
from: KURT KUZBA
date: 1998-03-25 05:34:00
subject: passing by reference

MM>   I suddenly found out that the way to declare a copy
MM>   constructor (not bothering with the specifics of any
MM>   class so I'll just write an ordinary function):
MM> void afunction(int &var1)
MM> {
MM>   var1=546;
MM> }
MM> void main()
MM> {
MM>   int k;
MM>   afunction(k);
MM>   Is it just me who's having a hell of a time thinking this
MM>   through or is this some sort of exception in the design
MM>   of the language whereby a '&' character can be used to
MM>   get the compiler to automagically work out all the pointer
MM>   stuff?  :-]
   Yes. :)
   The & means that the address is passed in the first instance,
   where you did: afunction(&k);
   In the latter instance, you also accept an address as an
   argument, and assign that address to your variable, var1,
   making it an alias for k in the calling function.
   It is the same variable by another name.
   Would it not smell as sweet?
   This is called passing a reference, and is not to be
   confused with passing BY reference, as with example 1, where
   you accept an argument of *var1, which is an integer value,
   usually a long integer, which is the address of the variable
   to be referenced. In languages such as BASIC, passing a
   reference to a variable is the ONLY way to pass a variable,
   other than by value, and is new in C++, not being found in C.
   A pointer is a reference to a variable, and that pointer must
   be de-referenced in order to manipulate the variable.
   A reference is an alias for a variable, and does not need to
   be dereferenced. The variable accepted IS the variable which
   was passed, under another name, which brings it into scope
   in the called function as a local variable.
> ] Boredom is the fear that your fun is catching up to you.....
---
---------------
* Origin: *YOPS ]I[* 8.4 GIG * RA/FD/FE * Milwaukee, WI (1:154/750)

SOURCE: echomail via exec-pc

Email questions or comments to sysop@ipingthereforeiam.com
All parts of this website painstakingly hand-crafted in the U.S.A.!
IPTIA BBS/MUD/Terminal/Game Server List, © 2025 IPTIA Consulting™.