c++enumsoperator-overloadingpre-increment

How to overload the ++ operator for a enum in C++


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;
}

Solution

  • 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&).