When we have,
struct E { enum E_ { HELLO }; }; // 'E' is inheritable
then why do we need,
enum class E { HELLO }; // 'E' is not inheritable
IMO 2nd version doesn't offer more features than the 1st. I don't think that enum class
is introduced just to save 2 curly braces {};
! Am I missing any important aspect ?
As a minor question, is there any difference between enum class
and enum struct
other than syntax (because both have public
access specifier) ?
Enumeration or Enum in C is a special kind of data type defined by the user. It consists of constant integrals or integers that are given names by a user. The use of enum in C to name the integer values makes the entire program easy to learn, understand, and maintain by the same or even different programmer.
Enums are lists of constants. When you need a predefined list of values which do represent some kind of numeric or textual data, you should use an enum. You should always use enums when a variable (especially a method parameter) can only take one out of a small set of possible values.
C treats enums as a type. Try doing a web search for "C enum type", and you'll find some proper links. Here is an explanation of the difference between enum type and class.
An enum type is a special data type that enables for a variable to be a set of predefined constants. The variable must be equal to one of the values that have been predefined for it.
Besides what was already mentioned, an advantage of enum class
is better type safety - the enum class
enumerators don't convert implicitly to integers.
Do we really need “enum class” in C++0x?
No, we don't "need" enum class
. We can get sufficiently equivalent functionality in other ways. But by that logic, we don't "need" a lot of stuff in C++. We don't "need" virtual functions and inheritance, since we can just implement it manually with vtables and such. We don't "need" member functions; these can be emulated by having them take an additional argument.
Language features exist to make programmers lives easier. Just because something can be done manually doesn't mean that it should.
enum class
has the following properties:
enum class
, but that's true for most new features. Once you get used to it, it's fine.enum class
definitions. Without this macro, you have to spend quite a bit of effort getting all of the corner cases to work. And even so, someone had to write and debug that macro.So no, we do not "need" them. But they're still a great addition to the language.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With