onsdag 9. april 2014

[ C++11 - Part 1 ] Enum classes

Introduction to the series


I thought I'd start of by talking about my favorite thing that's new about C++11 standard. C++11 has a lot of useful new features : auto, initializer lists, lambda, shared_ptr, unique_ptr, move semantics, etc. Some of these are quite comprehensive and complicated, and I'm still working on understanding all of them. But this one is actually quite simple.

About enum classes


Enum classes are basically enumerations that can't implicitly be converted to integer types. So basically you can't write :



Why is this such a good thing?


First of all it helps code clarity. A simple question : Say you have an enum of card suits, which would you prefer?



So it helps code clairty. Is that all?


No, there are more serious issues. Say you have the following code


This might look okay, they both set the card to Suit::Clover. But here comes the big issue. Someone changes the order of the elements in Suit.



What's the issue?


It might seem a very subtle change. But you let's say you implemented reset method a long time ago. It's been working fine ever since, and you've completely forgotten that it uses and integer value to set suit. It'll now do something different from the constructor! So you end up with cards being different when you reset them from when you create them. And issues like this can be very confusing to debug.

This is just a minimal example to showcase the issue. But this can happen just as easily in huge projects where the enum is used hundreds of places. Debugging such issues will waste a huge amount of time and cause a whole lot of pain and agony. All because of using an integer to assign an enum! Using enum class prevents these issues.

Conclusion


Use enum classes! It might be a bit annoying having to write the full enumeration name sometimes. But it's a lot better than spending hours upon hours debugging when someone changes the order of the enumeration items or adds a new value in front of others!


Feel free to comment if you have anything to say or ask questions if anything is unclear. I always appreciate getting comments.

For a full list of my tutorials / posts, click here.

Ingen kommentarer:

Legg inn en kommentar