KomeilR
KomeilR

Reputation: 90

is it possible to overload the increment operator (++) to increment by more than 1?

Is it possible to overload the increment operator (++) to increment by more than 1? If yes, isn't that violating the way the operator is supposed to function?

Upvotes: 1

Views: 157

Answers (3)

MSalters
MSalters

Reputation: 180010

Pointer arithmetic already does this, in a sense. It increments by sizeof(*ptr) bytes. Of course, that's so that you move to the next object, so it logically is an increment of one.

This is a common theme in C++. Overloading should behave logically correct; the internal details have to follow. For a linked list, operator++ should move to the next element in the list, not the next element in memory. Internally that typically translates to something like ptr = ptr->next instead of ptr = ptr+1.

Upvotes: 1

Pete Becker
Pete Becker

Reputation: 76438

For a user-defined type, overloading the increment operator only means that you've provided a function that can be called with ++. That is, it's just a syntactic convenience; it does not impose any restrictions on what that function does. So, yes, you can write it to increment by more than one. You can also write it to always return 42, or launch a game of Tetris. Of course, when you're designing such a function you have to consider whether its behavior would surprise someone who is using your code.

Upvotes: 0

Konrad Rudolph
Konrad Rudolph

Reputation: 545943

For custom types: Yes you can.

isn't that violating the way the operator is supposed to function

If your type models a number, then yes, absolutely. Which is why this usually is a very bad idea indeed. However, ++ more generally means “go to the next logical element”. For a numeric type, this is indeed expected to be 1 more than the current value.

But the operator generalises to sequences, which can have other properties. In the example given by Jesper, if your type represents the sequence of the Fibonacci numbers, then ++ should progress the sequence to the next Fibonacci number (and similarly for other sequences).

Incidentally, C++ does have an “increment by n” operator: +=.

Upvotes: 7

Related Questions