views:

259

answers:

5

How to differentiate between overloading the 2 versions of operator ++ ?

const T& operator ++(const T& rhs)

which one?

i++;
++i;
+3  A: 

for the postfix ++ and -- operators, the function must take a dummy int argument. if it has no argument, then it's the prefix operator

newacct
+10  A: 

These operators are unary, i.e., they do not take a right hand side parameter.

As for your question, if you really must overload these operators, for the preincrement use the signature const T& operator ++(), and for the postincrement, const T& operator(int). The int parameter is a dummy.

Daniel Daranas
They can be non-member functions.
Georg Fritzsche
@gf True. But that wouldn't be my first choice for increment operators. (My first choice would be to not overload operators, anyway.)
Daniel Daranas
@Daniel: You have no choice if you want to write a C++'ish iterator or iterator-alike object.
Zan Lynx
@Zan Lynx Ok, ok :)
Daniel Daranas
@Zan: ... unless you use boost.iterator to help you with that ;)
UncleBens
@Zan, that's new to me. Why would you need a nonmember if you want to add `op++` to your iterator?
Johannes Schaub - litb
@Johannes: I didn't say anything about needing a member or nonmember operator. I just said that you need to overload increment operators to make iterators.
Zan Lynx
@Zan ah then i misunderstood your statement to apply to the first part of his comment. Never mentioned :)
Johannes Schaub - litb
+2  A: 

Think of postfix increment i++ as having a second (missing) parameter (i.e. i++x). So postfix increment signature has a righthand parameter while the prefix increment does not.

R Samuel Klatchko
+9  A: 

For the non-member versions, a function with one parameter is prefix while a function with two parameters and the second being int is postfix:

struct X {};
X& operator++(X&);      // prefix
X  operator++(X&, int); // postfix

For the member-versions, the zero-parameter version is prefix and the one-parameter version taking int is postfix:

struct X {
    X& operator++();    // prefix
    X  operator++(int); // postfix
};

The int parameter to calls of the postfix operators will have value zero.

Georg Fritzsche
@gf add an example and this would be the best answer
caspin
@Caspin: Good point, done.
Georg Fritzsche
A: 

...........................................................................................

georgebcc