Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!cerc.utexas.edu!lynch From: lynch@cerc.utexas.edu (Tom Lynch) Newsgroups: comp.lang.c++ Subject: Re: Why use reference type over pointer type? Summary: can use on left side of assignment Keywords: reference & Message-ID: <1990Aug4.030723.25637@cerc.utexas.edu> Date: 4 Aug 90 03:07:23 GMT References: <1676@dinl.mmc.UUCP> <5720@darkstar.ucsc.edu> <21810@lute.com> Sender: Tom Lynch Followup-To: lynch@cerc.utexas.edu Distribution: na Organization: University of Texas at Austin Lines: 57 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 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