Quantcast
Viewing latest article 5
Browse Latest Browse All 5

Understanding C++ 0x: Type safe enumerations

The problem:

It takes only a quick switch to a language like PHP to recognize how handy enumerations (‘enums’) are in C++. Enumerations are especially useful for mapping from hard-to-express real-world concepts to code. For example:

enum Colors {
   Blue,
   Green,
   Purple
};
enum Animals {
   Donkey = 1,
   GiantSquid,
   Gazelle
};

Colors favoriteColor = Blue;
Animals desiredModeOfTransportation = GiantSquid;

The above declarations are essentially shorthand for the following:

// Note that enumerations, unless otherwise specified, start at 0
const int Blue = 0, Green = 1, Purple = 2;
const int Donkey = 1, GiantSquid = 2, Gazelle = 3;

Enumerations also give the syntactic sugar of being able to write things like ‘Colors favoriteColor;’, which translates to ‘int favoriteColor;’. In the past, though, C++ programmers have run into a strange problem in that enumerations aren’t type safe. This yielded strange results, such as:

Colors myFavoriteColor;
void SetFavoriteColor(Colors newFavoriteColor)
{
   myFavoriteColor = newFavoriteColor;
}

int main()
{
   SetFavoriteColor(Donkey); // ?
}

You see, even though you said in your function that you were expecting something of type ‘Colors’, underneath ‘Colors’ were integers just like ‘Animals’, so C++ had no problem compiling your seemingly erroneous code. Essentially, because both ‘Green’ and ‘Donkey’ evaluate to 1, they can be used interchangeably. As seen above, this is not always the desired behavior.

The solution:

The wonderful thing is that C++ 0x gives us the ability to have type safe enumerations. The best part is that they’re incredibly easy to use – all that it takes is to put the ‘class’ keyword in the enumeration declaration. For our above two enumerations, the declarations now look like:

enum class Colors {
   Blue,
   Green,
   Purple
};
enum class Animals {
   Donkey = 1,
   GiantSquid,
   Gazelle
};

You can think of it this way: if you want the same type safety that classes offer, you have to add the ‘class’ keyword after ‘enum’ to supply that type safety. In the above example, ‘SetFavoriteColor(Donkey);’ will now cause a compile-time error. Very simple and undeniably useful!


Viewing latest article 5
Browse Latest Browse All 5

Trending Articles