2.1.3 Scoped Enumerations

What was the problem

An enumeration in pre-C++11 code is just like a C enumeration: a list of constants of type int in the scope containing the enumeration. For example, note how appliance::fan can be accessed directly and assigned to an integer in the code below:

enum appliance 
{ 
  fan, 
  oven 
}; 
 
int main() 
{ 
  int v = fan; 
  return 0; 
}

While this is nice when we actually want the values of the enumeration to be an alias for integer constants, for example to store bit field flags, it can quickly become a mess when the entries of different enumerations share the same identifier in the same scope.

enum appliance 
{ 
  fan, 
  oven 
}; 
 
enum follower 
{ 
  fan, 
  admirer 
};

The above code will fail to compile with a message along the lines of “error: ‘fan’ conflicts with a previous declaration.” Now the typical solution to that was to add a unique prefix to the enumerated values, but in the times of namespaces and so, is it really a solution?

How the Problem is Solved

A scoped enumeration as introduced in C++11 is declared by adding the class or struct keyword between enum and the identifier. Additionally the storage type of the values can be defined too:

enum class appliance 
{ 
  fan, 
  oven 
}; 
 
enum class follower : char 
{ 
  fan, 
  admirer 
};

With these declarations the values are scoped in their respective enumerations and do not conflict with each other; so if we want to access a value we must now prefix it with the name of the enumeration, like in follower::fan. Moreover, they are also not implicitly convertible to int anymore, which may or may not always be a good thing.

The fact that we can also define the type of their values allows for smaller memory consumption when needed, but also add the possibility to use longer-than-int values. Nevertheless, I usually don’t specify this type unless necessary since it has to be repeated when the enumeration is forward declared. This repetition adds coupling and complicates any change in the type, for something that look like implementation details to me.