3

This is what I tried, but I see that overloading only increments the variable if I assign it to another variable. I.e, The value of the variable on which I do the increment does not increase. So, in the example below variable newDay is THU but currentDay remains WED.

How do I define the overload operator to increment variable I am doing the operation on?

typedef enum days {MON, TUE, WED, THU, FRI, SAT, SUN} days;

inline days operator++ (days& d) {
    return static_cast<days>((static_cast<int>(d) + 1) % 7);
}

int main(int argc, const char * argv[]) {
   days currentDay = WED;
   days newDay = ++currentDay;
   cout << "Current day: " << currentDay << ", Stored day: " << calendar[0] << ", New day: " << newDay << endl;
}
Arvind Swami
  • 83
  • 1
  • 7

2 Answers2

3

If I modify your overloaded operator to this:

inline days operator++ (days const& d) {
    return static_cast<days>((static_cast<int>(d) + 1) % 7);
}

It still compiles, despite the fact I added a const specifier there. That's because you are not modifying d like the semantics of prefix ++ demand.

So make sure you do modify it, if you want the operator to have the desired effect:

inline days operator++ (days& d) {
    d = static_cast<days>((static_cast<int>(d) + 1) % 7);
    return d;
}

Without commenting on the validity of your own design, note that it is a widely held opinion that prefix operator++ should return a modifiable lvalue, like the built-ins do. Bear in mind if you find yourself writing code like ++x = y, you need to return a reference, i.e. date& operator++(date&).

Steve Friedl
  • 3,929
  • 1
  • 23
  • 30
StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
-1

You defined the postfix operator. The normal behavior of the postfix operator is to increment the value of its argument but return the original value. It should behave like this:

days operator++(days& d,int){
    days temp=d;
    d=static_cast<days>((static_cast<int>(d) + 1) % 7);
    return temp;
}

What you want is the prefix operator. This increments the value of the argument and returns a reference to its arguments. It should look like this:

days& operator++(days& d){
    d=static_cast<days>((static_cast<int>(d) + 1) % 7);
    return d;
}
Johnathan Gross
  • 678
  • 6
  • 19