[comp.lang.c++] Why use reference type over pointer type?

noren@dinl.uucp (Charles Noren) (08/01/90)

Its obvious, I'm new to C++.
What does does a reference type give me over a pointer type
that I've come to love and know well in C?  It seems like the 
reference type is a syntatic cosmetic convenience to avoid the 
"->" operator inside functions.  Oh yes, there is also the
ability to alias references that the reference type provides.
My feeble mind, however, dulled by years of C programming and using
#define's (not to mention warped from poignant-pointed pointer 
use), fails to grasp the cosmic significance of the reference
type.  Perhaps some kind person, taking pity on my lowly
understanding of C++, could enlighten me in reference to
reference types.

Thanks,

-- 
Chuck Noren
NET:     dinl!noren@ncar.ucar.edu
US-MAIL: Martin Marietta I&CS, MS XL8058, P.O. Box 1260,
         Denver, CO 80201-1260
Phone:   (303) 971-7930

jeh@cs.rit.edu (Jim Heliotis) (08/02/90)

From article <1676@dinl.mmc.UUCP>, by noren@dinl.uucp (Charles Noren):
> Its obvious, I'm new to C++.
> What does does a reference type give me over a pointer type
> that I've come to love and know well in C?  ......

I, as a professor, have been asked this so many times that I would love
to hear people's opinions on this.

I personally prefer to use them because I like

	call-by-reference semantics
	"lvalue" - type variables

but I do not care for aliases.

I do have a hard time justifying their existence to more practically-minded
students, however.

				Jim Heliotis
				Rochester Institute of Technology
				Rochester, NY 14623-0887
				jeh@CS.RIT.EDU
				{allegra,seismo}!rochester!rit!jeh

jas@llama.Ingres.COM (Jim Shankland) (08/03/90)

In article <1806@cs.rit.edu> jeh@cs.rit.edu writes:
>From article <1676@dinl.mmc.UUCP>, by noren@dinl.uucp (Charles Noren):
>> Its obvious, I'm new to C++.
>> What does does a reference type give me over a pointer type
>> that I've come to love and know well in C?  ......
>
>I, as a professor, have been asked this so many times that I would love
>to hear people's opinions on this.
>
>I personally prefer to use them because I like
>
>	call-by-reference semantics
>	"lvalue" - type variables

It's not clear to me what you mean by these two that can't be had by
explicitly using pointer variables.

One place where references come in handy is when you define an operator
on a class, and you want the arguments to be passed by reference.  I.e.,
given a class Huge, with Huge h, i, and j, you can define
"friend Huge& operator+(Huge&, Huge&)", and thus say "h = i + j" while
still passing i and j to the operator function by reference.

Consider this puzzle:  suppose that assignment and initialization semantics
in C++ were altered such that referencing and dereferencing were performed
implicitly as needed.  That is, given:

X x, *xp;

you could say:

x = xp;		// rhs implicitly converted to *xp
xp = x;		// rhs implicitly converted to &x

just as you can currently say:

int i, double d;
...
d = i;		// i implicitly converted to (double) i

Some 60's language -- Algol 68? -- did this.

*Now* are references ever needed?  Note that the operator+ example above
could now be coded as "friend Huge *operator+(Huge *, Huge *)".
As near as I can tell, this makes the need for references disappear altogether.
I'd certainly be interested if anyone can prove me wrong ....

jas

culliton@cdss.UUCP (Tom Culliton x2278) (08/03/90)

In article <1806@cs.rit.edu>, jeh@cs.rit.edu (Jim Heliotis) writes:
> From article <1676@dinl.mmc.UUCP>, by noren@dinl.uucp (Charles Noren):
> > Its obvious, I'm new to C++.
> > What does does a reference type give me over a pointer type
> > that I've come to love and know well in C?  ......
> 
> I, as a professor, have been asked this so many times that I would love
> to hear people's opinions on this.

The clearest value that I've found is getting the syntax/semantics of
overloaded operators (and some other member functions) right while
maintaining the efficiency of pointers.  There are some other cases in
the development of classes where using a reference "just makes it feel
right", Of course I can't clearly state exactly when this is. ;-)

                                                      Tom
*****************************************************************************
*  uunet!culliton@cdss - Tom Culliton at Arinc Research Corp. Annapolis MD  * 
*       "I haven't lost my mind -- it's backed up on tape somewhere."       *
*****************************************************************************

ericg@ucschu.ucsc.edu (Eric Goodman) (08/04/90)

For a C programmer, there may not be much difference (although I hate 
*****p=***q as a command, my eyes are too feeble to comprehend it at a 
glance), but to programmers just starting out, it's a nice mechanism to 
limit confusion (although my guess it you might see it more as a mental 
crutch that might ultimately be more confusing than helpful).

I also like it, and don't mind making the computer do my dereferencing for 
me.

Eric Goodman
UC Santa Cruz

ericg@ucschu.ucsc.edu                              ericg@ucschu.bitnet
Eric_Goodman.staff@macmail.ucsc.edu      ...!ucbvax!ucscc!ucschu!ericg

frose@synoptics.COM (Flavio Rose) (08/04/90)

The beauty of the C way of doing call-by-reference is the
following:

Suppose you are reading or debugging someone else's code (a
very common activity), and you come across a call

	foo(a,b,&c);

and a, b, c are of scalar type. Then you can say
immediately, without bothering to look up foo's function
prototype anywhere, "aha, foo munges c but not a or b."
Often you don't care to know more about foo() than that, so
this saves time and doesn't make you interrupt your train
of thought to look up a prototype.

(I think liking little old-fashioned conveniences of this
kind makes one fall into a kind of pattern, which I call
"troglodytic programming." In opposition to troglodytic
programmers we find the futurists, who always follow the
latest fad, place an assertion after every statement so
their code will be fully self-checking, and are eager to
reach the Nirvana of "nonprocedural code.")

lynch@cerc.utexas.edu (Tom Lynch) (08/04/90)

The one situation I have found where a reference is necessary is
when returning an lvalue to the left side of an assignment.

say I have the class:
      
#include <stream.h>
      class safe_int_array{
           int *data;
           int max_dex;
         public:
           safe_int_array( int size ){ 
                data = new int[size];
                max_dex = size - 1;
           }

           int & operator[](int index){
                 if( index < 0 || index > max_dex ){
                     cerr << "illegal array access \n";
                     exit(1);
                 }else
                     return data[index];
            }
       };/*end class*/


The safe_int_array may be assigned to:

     main(){

           safe_int_array x(7);
           for(int i = 0; i < 7; i++){  //initialize the array
             x[i] = i;
           }
           for( i = 0; i < 7; i++){ //prints: 0123456
             cout << x[i];
           }
           cout << "\n";
    }
       
        
Safe arrays should interest students.  However, returning references
can be very dangerous.  Returning a reference to a local variable can
go unnoticed.  We played with this
and found that the free-ed storage that holds the old subroutines 
local variables will keep the old value until an expression is 
evaluated or another function is called.  By our experience, this is 
the kind of bug which beginners have a very difficult time finding.
It is also hard to explain: "a references is not a pointer but it is..."

I think it is easier to keep track of the C pointer notation in C++
programs; although because references require less typing they
are nice to use :-) :-).

Tom Lynch                           Nothing is absolute.
lynch@cerc.utexas.edu
        
               

mat@mole-end.UUCP (Mark A Terribile) (08/06/90)

> > Its obvious, I'm new to C++.
> > What does does a reference type give me over a pointer type
> > that I've come to love and know well in C?  ......

This sound like a candidate for an FAQ (frequently asked questions) list.
 
> I, as a professor, have been asked this so many times that I would love
> to hear people's opinions on this.
> 
> I personally prefer to use them because I like
> 
> 	call-by-reference semantics
> 	"lvalue" - type variables
> 
> but I do not care for aliases.
> 
> I do have a hard time justifying their existence to more practically-minded
> students, however.

Well, for one thing, by changing just the declaration for the CALLED function,
you control (with appropriate typechecking) whether you have call by copy-
value or call-by-reference.  This is definitely a maintanance win that ought
to interest practically-minded students.

For another, the type system considers  X&  to be the same as  X  for the
purpose of overloading resolution and conversions.  This means that the
same rules apply whether call-by-reference or call-by-value is involved.

There are good reasons to not allow overloads of  operator+( X* , X* ) ,
not the least of which is that the code using this operator would have
to be written in a strange way and that no member form would be possible;
these problems don't affect  operator+( X&, X& ) .

-- 

 (This man's opinions are his own.)
 From mole-end				Mark Terribile

sakkinen@tukki.jyu.fi (Markku Sakkinen) (08/07/90)

Note2: Third trial to post!
Note1: This is the second posting of an article that apparently
disappeared while the news software was out of order here
for three days. Sorry if somebody receives it twice.

In article <21810@lute.com> frose@synoptics.COM (Flavio Rose) writes:
>The beauty of the C way of doing call-by-reference is the
>following:
>
>Suppose you are reading or debugging someone else's code (a
>very common activity), and you come across a call
>
>	foo(a,b,&c);
>
>and a, b, c are of scalar type. Then you can say
>immediately, without bothering to look up foo's function
>prototype anywhere, "aha, foo munges c but not a or b."
>Often you don't care to know more about foo() than that, so
>this saves time and doesn't make you interrupt your train
>of thought to look up a prototype.

Perhaps you should have stressed more that this is an argument
_against_ using reference declarations in the function prototype.
It is a good argument!
However, there are also cases in which the C way is very dangerous.
A prime example is the 'scanf' library function: anything may
happen if you forget to write '&' before all appropriate arguments,
and there is no possibility for compile-time checking because
the function has a variable number of arguments.

> ...

Markku Sakkinen
Department of Computer Science
University of Jyvaskyla (a's with umlauts)
Seminaarinkatu 15
SF-40100 Jyvaskyla (umlauts again)
Finland
          SAKKINEN@FINJYU.bitnet (alternative network address)

jimad@microsoft.UUCP (Jim ADCOCK) (08/09/90)

In article <422@mole-end.UUCP> mat@mole-end.UUCP (Mark A Terribile) writes:
>> > Its obvious, I'm new to C++.
>> > What does does a reference type give me over a pointer type
>> > that I've come to love and know well in C?  ......
>
>This sound like a candidate for an FAQ (frequently asked questions) list.

....

People who come from a C background look at C++ and say:
Why should I use references when I can do whatever I need to do using pointers?

People who come from a OOP background look at C++ and say:
Why should I use pointers when I can do whatever I need to do using references?

----

There is two distinct styles of OOP programming in C++.  In one style, use
of pointers predominates.  In the other style, use of references predominates.
Given either style, most people find using the other feature convenient,
occasionally.  People working together on one project probably
need to get together and decide which style is going to be used predominately
in that project.  Unfortunately, this also means that as C++ libraries become
available, they will generally follow one of these two distinct styles.

noren@dinl.uucp (Charles Noren) (08/09/90)

Thanks to all those who replied.  Its been two weeks since I started
really reading C++ books and writing C++ code.  My question looks
REALLY naive now.  While reference types are a convenience, they are
som amazingly convenient in *so* many circumstances that I view it
as a necessity.  For instance, when for an exercise I created array
and matrix classes, the overloading of the operator [] requires its
use (along with a host of other operators, such as +=) to permit the
natural use of the operators.  So to answer my question, reference types
are extemely useful in many areas of C++ programming and the question
just pointed to my lack of experience in the language.

Thanks for all the kind people who took pity on my lowly understanding
of C++ and gently enlightened me in reference to reference types.

-- 
Chuck Noren
NET:     dinl!noren@ncar.ucar.edu
US-MAIL: Martin Marietta I&CS, MS XL8058, P.O. Box 1260,
         Denver, CO 80201-1260
Phone:   (303) 971-7930

rhys@batserver.cs.uq.oz.au (Rhys Weatherley) (08/26/90)

sakkinen@tukki.jyu.fi (Markku Sakkinen) writes:

>In article <21810@lute.com> frose@synoptics.COM (Flavio Rose) writes:
>>The beauty of the C way of doing call-by-reference is the
>>following:
>>
>> ... [ description of how '&' in calls can tell you what's happening ] ...
>>
>>Often you don't care to know more about foo() than that, so
>>this saves time and doesn't make you interrupt your train
>>of thought to look up a prototype.

The problem is not that you have to look up the prototypes, but the
mechanism for looking them up is very annoying.  e.g. quit editor,
start up broswer, quit browser, startup editor and figure out where
the heck you were!! (or something like that :-).  In actual fact it
is probably a GOOD idea to look up the prototype of a function you
haven't seen before just to make sure!!

What is needed instead is a totally new way of looking at C and C++
programming using more integrated programming environments that
by just clicking the mouse, or pressing a key, you can instantaneouly
see the prototype and then go straight back to where you were.
Some environments such as Turbo C/Turbo C++ already provide some
facilites for this for their standard library routines, but this
needs to be extended to programs you write as well.

Some work is already been done around the world in this area, but
they still haven't REALLY reached the mass market yet.  So, environment 
writers, hop to it - us programmers need much better support at our end.

>However, there are also cases in which the C way is very dangerous.
>A prime example is the 'scanf' library function: anything may
>happen if you forget to write '&' before all appropriate arguments,
>and there is no possibility for compile-time checking because
>the function has a variable number of arguments.

Unfortunately, it is probably very difficult to deal with this in
environments :-(.  Maybe the format argument could be inspected to
try and determine whether the programmer has used correct types, but
this does not cope with code like the following:

	char format[3];
	int x;
	sprintf (format,"%%d");
	scanf (format,x);

So although environments will greatly help, there are still some warts!
But they'd be better than what we are using now!!

I would be very interested if anyone is doing some serious work in
the C/C++ programming environment area, as would be many others in this 
newsgroup I expect.

Rhys.

+===============================+==============================+
||  Rhys Weatherley             |  University of Queensland,  ||
||  rhys@batserver.cs.uq.oz.au  |  Australia.  G'day!!        ||
+===============================+==============================+