TIP: Click on subject to list as thread! ANSI
echo: c_plusplus
to: ALL
from: MICHAEL MCGAVIN
date: 1998-03-22 16:24:00
subject: passing by reference

Hi All,
I'm largely self taught in C/C++ but I've just started doing a more formal 
course in it.  Anyway, we just started covering copy constructors in classes 
which is something I haven't hit before.  It's not the idea of what it does 
that confuses me, it's the way the parameter is passed to it.
Whenever I want to pass something by reference I do it manually (as follows):
void afunction(int *var1)
{
  *var1=546;
}
void main()
{
  int k;
  afunction(&k);
}
- this works out logically as far as I can tell.  As in the declaration says 
that '*var1' is an integer, and so 'var1' by itself is a pointer to the 
integer.  Then I just make sure that when I call the function I pass a 
pointer to the integer instead of the integer itself.
So anyway, I suddenly found out that the way to declare a copy constructor is 
(not bothering with the specifics of any class so I'll just write an ordinary 
function):
void afunction(int &var1)
{
  var1=546;
}
void main()
{
  int k;
  afunction(k);
}
ie. An integer variable can just be passed to it ordinarily.  This is really 
confusing me.  :-)  I hate trying to work out where pointers are going and 
stuff but by my logic so far, '&var1' would be an integer and so 'var1' would 
be a junk value pointed to by whatever was currently in the integer.
Is it just me who's having a hell of a time thinking this through or is this 
some sort of exception in the design of the language whereby a '&' character 
can be used to get the compiler to automagically work out all the pointer 
stuff?  :-]
Thanks for any help.
Mike.                                   email: zog@sans.vuw.ac.nz
--- GoldEd 2.50 UNREG
---------------
* Origin: DARK SKIES Astronomy -- Wgtn, NZ. +64-4-235-6887 (3:771/1560.201)

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™.