devxlogo

Overloading Operator

Question:
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.

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

Charlie has over a decade of experience in website administration and technology management. As the site admin, he oversees all technical aspects of running a high-traffic online platform, ensuring optimal performance, security, and user experience.

See also  Seven Service Boundary Mistakes That Create Technical Debt

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.