[gnu.g++] What's the diff?

knutson@hsinchu.sw.mcc.com (Jim Knutson) (08/04/89)

What's the difference between the ++ operator overload functions in
these two examples?  The Lippman book (p. 197) prefers to define the
function type to return a reference to the class while the Pohl book
(p. 125) seems to prefer to return the class.  Both seem to work
equally well as both lvalue and rvalue.

class counter {
	int count;
public:
	counter() { count = 0; }
	counter(int c) { count = c; }
	counter& operator ++() { count++; return *this; }
	value() { return count; }
};

class counter {
	int count;
public:
	counter() { count = 0; }
	counter(int c) { count = c; }
	counter operator ++() { count++; return *this; }
	value() { return count; }
};

Jim Knutson
knutson@mcc.com
cs.utexas.edu!milano!knutson
-- 
Jim Knutson
knutson@mcc.com
cs.utexas.edu!milano!knutson

acw%illini@Sun.COM (Alex Wu [GPD] x6-6874) (08/05/89)

In article <2731@hsinchu.sw.mcc.com>, knutson@hsinchu.sw.mcc.com (Jim Knutson) writes:
> What's the difference between the ++ operator overload functions in
> these two examples?  The Lippman book (p. 197) prefers to define the
> function type to return a reference to the class while the Pohl book
> (p. 125) seems to prefer to return the class.  Both seem to work
> equally well as both lvalue and rvalue.
> 
> class counter {
> 	int count;
> public:
> 	counter() { count = 0; }
> 	counter(int c) { count = c; }
> 	counter& operator ++() { count++; return *this; }
> 	value() { return count; }
> };
> 
> class counter {
> 	int count;
> public:
> 	counter() { count = 0; }
> 	counter(int c) { count = c; }
> 	counter operator ++() { count++; return *this; }
> 	value() { return count; }
> };
> 

One difference I can think of is that the first class allows 
the cascade of "++" in this case, that is:

  counter i;
  (i++)++;
  cout << i.value() << '\n'; // gives 2

while the second one gives 1.
Alex Wu 
Sun Microsystems, Inc.
415-336-6874
acw@sun.com

dog@cbnewsl.ATT.COM (edward.n.schiebel) (08/07/89)

From article <119611@sun.Eng.Sun.COM>, by acw%illini@Sun.COM (Alex Wu [GPD] x6-6874):
>> these two examples?  The Lippman book (p. 197) prefers to define the
>> function type to return a reference to the class while the Pohl book
>> (p. 125) seems to prefer to return the class.  Both seem to work
>> equally well as both lvalue and rvalue.
>> 
...
> One difference I can think of is that the first class allows 
> the cascade of "++" in this case, that is:
> 
>   counter i;
>   (i++)++;

Also:
  By returning a reference, the result may be used as an lvalue.
  (i++) = something else;

  If used on the right hand side of an assignment i.e. j = i++, return
  by reference (almost) guarantees a copy of the object is not 
  created in the process.

	Ed Schiebel
	AT&T Bell Laboratories
	att!vilya!dog