Overloading Operator

Overloading Operator

How do I overload the ++ operator to work with an enum variable? For example, I defined SuitType to be {Heat, Club, Diamond, Spade}. I want to use s++ (where s is a variable of SuitType) so that it will advance s from Hearts, to Clubs, to Diamonds, etc.

I’ll give an example of operator ++. Overloading operator ++ for an enum type consists of the following steps.

First you check whether the enum variable has the highest enumerator value. In that case, you perform a rollover by assigning the lowest enumerator value to it. Otherwise, you simply cast the enum variable to an int, increment it, cast that int back to the enum type, and return the result.

Here is a complete example of overloading ++ for the days of the week:

 enum Days {Mon, Tue, Wed, Thur, Fri, Sat, Sun};Days& operator ++ (Days& d) //overloaded operator{  if (d == Sun)     return d = Mon; //rollover  int temp = d;  ++temp;  return d = static_cast (temp); }int main(){ Days day = Mon; ++day;  // day now equals Tue return 0;} 

See also  5 Tips for Working With an Onsite Interpreter

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist