nomnom
nomnom

Reputation: 1638

Correct return type for the operator ++

I am trying to implement a List and Iterator classes (our homework, we should implement our own list in stl style). I have a question about the ++ operator. In my implementation, the ++ does not return anything:

void operator++();

But a friend of mine implemented it like this:

Iterator& operator++();

I tested both of them, and it seems both of them work. But I believe there must be some big difference. But I am a newbie to C++ language. So I can't see it. Could anyone please help me?

Upvotes: 2

Views: 89

Answers (3)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

The difference is that his operator can be used as if the iterator was a pointer, while yours cannot. With pointers, you can do this:

char *p1, *p2;
...
p1 = ++p2;

For this to work with iterators, the ++ operator must return the value before (or after) the increment, depending on the pre- or post- position of the operator. Your implementation does not do that. Although it is technically OK, the resultant operator is not as functional, so it is a good idea to change your implementation to return a value.

Upvotes: 1

unkulunkulu
unkulunkulu

Reputation: 11912

The common convention here is that overloaded operators should resemble ordinary ones. For example, you can:

int x = 5;
int y = ++x;

So your iterators really should be usable in the similar context:

Iterator i = smth.begin();
Iterator j = ++i;

Your friend's version allows this.

There's also an old C joke:

++i = 0;

So yes, your operator ++() should return *this as an lvalue to allow this kind of stuff so the return type is Iterator& and not Iterator or const Iterator&.

Upvotes: 3

Fred Foo
Fred Foo

Reputation: 363507

The difference is that your friend's version can be called in forms like

// loop that skips the first element
while (++it != end)
    // perform operation

where it is some iterator. Library functions and client code may depend on this, so always return *this from an overloaded operator++. All standard library iterators work this way and so do the pointers on which they are modeled.

Upvotes: 1

Related Questions