Search code examples
c++operator-overloadingdecrementpostfix-operator

What is the extra argument used for when overloading the decrement operator?


When I overload the post-decrement operator, I have to include a extra argument:

#include <iostream>

template<class T>
class wrap
{
public:
    bool operator >(T &&v)
    {
        return value > v;
    }
    T operator --(int v) // Remove 'int v' and you get a compilation error
    {
        return (value -= 1) + 1;
    }
    wrap(T v)
    {
        value = v;
    }
private:
    T value;
};

int main(void)
{
    wrap<int> i(5);
    while(i --> 0)
        std::cout << "Why do we need the extra argument?\n";
    return 0;
}

If I remove this seemingly unneeded argument, I get a compilation error:

test.cpp: In function ‘int main()’:
test.cpp:26:13: error: no ‘operator--(int)’ declared for postfix ‘--’ [-fpermissive]
     while(i --> 0)
           ~~^~

What is this argument used for? What does its value represent?


Solution

  • There are two separate but related overloads of operator++ - pre-increment and post-increment. Both are overridable. Since they both have the same name, the designers of C++ had to decide on a syntax to let the compiler differentiate between them. They chose to use a dummy int parameter on the post-increment operator.

    When you write code like this:

    wrap<int> i(5);
    ++i; // <-- calls i.operator++();
    

    The compiler emits code to call the parameter-less operator++().

    When you write code like this instead:

    wrap<int> i(5);
    i++; // <-- calls i.operator++(0);
    

    The compiler emits code to call the parametered operator++(int), passing 0 for the dummy parameter.

    The value of the parameter is meaningless, its mere presence is enough to let each overload of operator++ be overriden individually since they have different signatures.

    BTW, the same rules apply to the pre/post-decrement operator-- as well.