c++ post and pre increment operators - slightly off topic

llewelly@dbritsch.dsl.xmission.com llewelly@dbritsch.dsl.xmission.com
Wed Jul 26 05:25:00 GMT 2000


On Tue, 25 Jul 2000, Gianni Mariani wrote:

> 
> Please excuse my digression, it seems I have run out of other
> references.

In the future, please post C++ questions to comp.lang.c++.moderated; you
  will usually get more and better answers.

> 
> It seems c++ post increment methods don't happen post the expression.
> 
> A class that implements operator++() operator++(int) and operator*()
> does not behave like (I at least) expected.
> 
>     int i = * pointer_val ++;
> 
> Seems to behave differently if pointer_val is a real pointer.  The post
> increment operator happens BEFORE the reference.
> 
> Am I missing somthing.  Same thing happens on windoze.
> 
> ------- output of the code below --------
> 
> perator++(int) called
> operator*() called
> operator++() called
> operator*() called
> x1=1 x2=1            <<< --
> x1=0 x2=1            <<< -- expected these 2 lines to be the same.
> 
> ------- the code below ----------
> 
> 
> #include <iostream.h>
> 
> class foo {
> public:
>     int         i;
> 
>     foo( int x = 0 )
>         : i( x )
>     {
>     }
> 
>     int operator*()
>     {
>         cout << "operator*() called\n";
>         return i;
>     }
> 
>     foo operator++()
>     {
>         cout << "operator++() called\n";
>         ++ i;
>         return * this;
>     }
> 
>     foo operator++(int num)
>     {
>         cout << "operator++(int) called\n";
>         i ++;
>         return * this;
>     }

foo::operator++(int) is supposed to make a copy of *this, increment *this
  (leaving the copy unchanged), and return the copy:

      const foo operator++(int)
      {
         foo ret(*this);
         operator++();
         return ret;
      }
   
   should work the way you expect.

> 
> };
> 



More information about the Gcc-help mailing list