Reputation: 21
I was looking at an iterator class for a linked list and saw this operator overloading and didn't really understand what was going on. I was under the impression that 'int' always has to be declared with a variable name?
void operator++(int)
{
assert(m_node != NULL);
m_node = m_node->m_next;
}
void operator--(int)
{
assert(m_node != NULL);
m_node = m_node->m_prev;
}
Upvotes: 2
Views: 71
Reputation: 149
Because you have two ++ operators, it is a special syntax to differentiate them between post- and pre- incrementation.
void operator++(int)
means postincrementation
void operator++()
means preincrementation
So in your case, you first return, then increase.
Upvotes: 2
Reputation: 254451
You can always leave out a parameter name if you want to. If you do that in a normal function definition, that means that an argument must still be provided to the function, but the function doesn't use it:
void f(int) // unnamed parameter
{
// can't use the parameter without a name
}
f(); // ERROR: wants an int
f(42); // OK: takes an int (but ignores it)
In the case of the increment and decrement operators, an unused int
parameter is the magic that indicates that this is the postfix operator, x++
, not the prefix operator, ++x
, which has no parameters.
Upvotes: 4
Reputation: 10733
void operator++(int)
This means post increment operator. int is just a dummy variable to distinguish it from pre-increment operator. Compiler would pass 0 in its place when calling post increment operator.
Upvotes: 1
Reputation: 96810
Parameter names are always optional. However, the int
in this case is special as it denotes this is a postfix operator meaning you are able to do list++
and list--
.
Reference: http://en.cppreference.com/w/cpp/language/operators
Upvotes: 4