How to differentiate (when overloading) between prefix and postfix forms of operator++? (C++)
Asked Answered
D

4

8

Because I've overloaded the operator++ for an iterator class

template<typename T>
typename list<T>::iterator& list<T>::iterator::operator++()
{
    //stuff
}

But when I try to do

list<int>::iterator IT;
IT++;

I get a warning about there being no postifx ++, using prefix form. How can I specifically overload the prefix/postifx forms?

Diaconate answered 21/5, 2009 at 19:55 Comment(0)
N
13

Write a version of the same operator overload, but give it a parameter of type int. You don't have to do anything with that parameter's value.

If you're interested in some history of how this syntax was arrived out, there's a snippet of it here.

Negotiate answered 21/5, 2009 at 19:56 Comment(1)
For an example of a free function, see these Q & A.Guerdon
C
21

(Edit: the link that used to stand here no longer works. quoting directly from the original text by Danny Kalev)

For primitive types the C++ language distinguishes between ++x; and x++; as well as between --x; and x--; For objects requiring a distinction between prefix and postfix overloaded operators, the following rule is used:

class Date {
    //...
    public:
    Date& operator++(); //prefix
    Date& operator--(); //prefix
    Date operator++(int unused); //postfix
    Date operator--(int unused); //postfix
};

Postfix operators are declared with a dummy int argument (which is ignored) in order to distinguish them from the prefix operators, which take no arguments.

Christianchristiana answered 21/5, 2009 at 19:56 Comment(2)
Postfix operators should return by value, not reference. I guess there might be very strange situations where they can return a reference, but what to? Not this, because it has been incremented...Formenti
The link you gave is now completely unrelated to C++ operator overloading.Guerdon
N
13

Write a version of the same operator overload, but give it a parameter of type int. You don't have to do anything with that parameter's value.

If you're interested in some history of how this syntax was arrived out, there's a snippet of it here.

Negotiate answered 21/5, 2009 at 19:56 Comment(1)
For an example of a free function, see these Q & A.Guerdon
I
8

Postfix has an int argument in the signature.

Class& operator++();    //Prefix 
Class  operator++(int); //Postfix 
Ivan answered 21/5, 2009 at 19:57 Comment(0)
A
0

A lot of information about operator overloading can be found in Operator Overloading, C++ FAQ.


Edit:
The original link (http://www.parashift.com/c++-faq-lite/operator-overloading.html) meanwhile resolves to the collection linked above.

Antenatal answered 22/8, 2011 at 15:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.