Search code examples
c++classoperator-overloadingpostfix-operator

C++ Overloading '--' postfix operator


I'm trying to overload the '--' postfix operator. I have this code:

class Counter
{
 private:
    int count;
 public:
    Counter()
    { count = 0; }
    Counter(int c)
    { count = c; }

    void setCount(int c)
    { count = c; }
    int getCount()
    { return count; }

    int operator--()
    {
       int temp = count;
       count = count - 1;
       return temp;
    }
};

Then in main I have this function call:

 Counter a; 
 a.setCount(5); 
 cout << a-- << endl;

This gives me this error: error: no ‘operator--(int)’ declared for postfix ‘--’, trying prefix operator instead

But when I call the operator-- function like this, it works just fine:

 cout << a.operator--() << endl;

What gives? It should be working fine.


Solution

  • For overloading postfix operator you need to specify a dummy int argument in the function signature i.e. there should also be a operator--(int). What you have defined is a prefix decrement operator. See this FAQ for more details.