top of page
altaybrusan

Enum vs Strongly typed enum

Updated: Aug 7, 2022





Old-style enums do not have their own scope. Any name used in an enum could not be used in the other enums which are defined in the same scope.





enum Animals {Bear, Cat, Chicken};
enum Birds {Eagle, Duck, Chicken}; // error! Chicken has already been declared

In this example Chicken is already defined in Animals. So, it is not possible to use it in Birds.


enum class Fruits { Apple, Pear, Orange };
enum class Colors { Blue, White, Orange }; // no problem!

The old style could cause confusion. They are indeed integral type (for example integer), so we use it like:


bool b = Bear && Duck;

There is no problem in this code, but it is strange! But for strong typed variables we can not do this:


bool _b = Fruits::Apple && Colors::Orange;

As a final note, we can specify underling integral type of C++11 enums:



enum class Foo : char { A, B, C };


4 views0 comments

Recent Posts

See All

smart pointers

The code we just described is fully functional, but, it can be strengthened, specifically with the function, AlbumDao::albums(). In this...

Comments


bottom of page