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?

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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...
The link you gave is now completely unrelated to C++ operator overloading.
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.

1 Comment

For an example of a free function, see these Q & A.
8

Postfix has an int argument in the signature.

Class& operator++(); //Prefix Class operator++(int); //Postfix 

Comments

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.

Comments