[Discuss] OT - C++ operator overloading question.

John Vetterli jvetterli at linux.ca
Wed Aug 30 12:36:06 PDT 2006


On Wed, 30 Aug 2006, John Vetterli wrote:
> Also, IIRC, operator++() and operator--() define postincrement and 
> postdecrement operators; use operator++(int) and operator--(int) to define 
> preincrement and predecrement (the int is just a dummy value).

Oops (mine, this time):  I got the pre- and post- reversed.

To check:

class foo
{
private:
   int n;
public:
   foo (int m) : n (m) { }
   foo operator++ () {std::cout << "void" << std::endl; return foo (n);}
   foo operator++ (int) {std::cout << "int" << std::endl; return foo (n);}
};

int
main (int argc, char* argv[])
{
   foo bar (1);
   ++bar;
   bar++;
   return 0;
}

Compiled using g++ 3.3.5.
The output:
void
int

In summary:
   operator++() is pre-increment
   operator++(int) is post-increment

Sorry about that
JV


More information about the Discuss mailing list