TIP: Click on subject to list as thread! ANSI
echo: aust_c_here
to: David Nugent
from: Greg Newton
date: 1995-03-18 14:23:12
subject: C++ - overloading pre/post-increment/decrement operators

G'day David,

Replying to a message of David Nugent to Greg Newton:

 >> Can anyone tell me why it should be (or is) necessary to
 >> provide the capability to overload both pre and post
 >> operators?  Surely one is interchangeable with the other,

 DN> No, they aren't interchangable. The effect of:

 DN>     int x,i;
 DN>     x = i++;

 DN> is clearly different to

 DN>     int x,i;
 DN>     x = ++i;

Yes, I have understood this for a long time.

 DN> Why shouldn't more complex objects behave in much the same fashion?


 >> the compiler should determine to call the overload function
 >> either before or after the expression it's in is evaluated.
 >> Is there something I'm missing here?

 DN> There's a logical difference between the two.

 DN> Say we put the increment operators (both post- and pre-) into an
 DN> iterator class. It might have the following members:

 DN>  class Iterator
 DN>  {
 DN>   public:
 DN>     // ...
 DN>     int operator++();
 DN>     int operator++(int);
 DN>     int current();          // There is valid "current"
 DN>     // ...
 DN>  };

 DN> Now the result of the ++ operators might differ according to function
 DN> - logically it should. On the one hand, the pre-increment operator
 DN> would return the state AFTER the iterator moves to the 'next', and
 DN> BEFORE in the post-iterator case.

 DN> This rationale, like all operator overloading in C++, is on the basis
 DN> that classes should be allowed to behave as much like intrinsic types
 DN> as possible, so that expressions LOOK logical and have a more
 DN> intuitive meaning.

Yes, now I see why it's necessary.  I was restricting my thinking to more
basic data types, I guess... whereas I should have thought (pardon me if
this isn't clear to you, it helps for me :) more of *p++ vs. *(++p). i.e.
an iterator of sorts vs. an int or whatever.

 >> if( C++ == ++C ) exit(ERROR);

 DN> Ah, the behaviour in this expression is "undefined" under
ISO C (and
 DN> therefore C++). You might get different results with different
 DN> compilers, but any which way it turns it, it is definitely not an
 DN> error.  :-)

Hey, I knew that!

Thanks for that... it's much clearer.

Cheers,
Greg |;^)

--- FleetStreet 1.02 NR
* Origin: (3:639/666)
SEEN-BY: 50/99 54/54 620/243 623/630 632/348 386 998 633/371 634/384 635/301
SEEN-BY: 635/502 503 541 544 636/100 639/100 666 711/401 409 410 430 510 807
SEEN-BY: 711/808 809 932 934 712/515 713/888 714/906 800/1 7877/2809
@PATH: 639/666 100 635/503 50/99 711/808 809 934

SOURCE: echomail via fidonet.ozzmosis.com

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