C++ enum class vs enum

C++ LogoI’d read about enum class in C++. It’s a slight strengthening of the compiler checking compared to plain old enums.¬† Why you may wonder? Well,

  • Conventional enums can implicitly convert to int, causing errors when someone does not want an enumeration to act as an integer.
  • Conventional enums export their enumerators to the surrounding scope, causing name space pollution.
  • The underlying type of an enum¬†cannot be specified, causing confusion, compatibility problems, and makes forward declaration impossible.

Additionally you can declare the underlying storage type, which lets the compiler catch bugs where a value is too large for the storage. Here’s a made up example to show this:


enum class byteThings : unsigned char {
Thing1 = 0x01,
Thing2 = 0x02,
Thing3 = 0x04,
BigThing = 0x120  // Compiler will complain!
}

The downside is that to get the int value, you now need to do a static cast but it does make your code safer.

byteThings b = Thing2; 
int i= static_cast(thing); // 2