rcorrie
rcorrie

Reputation: 921

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.

Upvotes: 0

Views: 3565

Answers (2)

Marlon
Marlon

Reputation: 20312

The postfix operator takes a int as an argument to distinguish it from the prefix operator.

Postfix:

int operator--(int)
{
}

Prefix:

int operator--()
{
}

Upvotes: 8

Naveen
Naveen

Reputation: 73483

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.

Upvotes: 8

Related Questions