Home > other >  what does it mean when we create instance of type, created using enum (and not enum class) in c
what does it mean when we create instance of type, created using enum (and not enum class) in c

Time:09-10

I recently got a comment from a SO user (on another account) that Enums are are used to create type and not instances! I wanted to cross-check with the community whether it's right. As far as I understand there is a plain enum (Enum-Type) and Enum Class in C . My que dealt with just enum and had not written enum class anywhere, So, I guess, the user was talking about Enum-Type. So, is it safe to assume that both Enum-Type and Enum-Class are used to create types? (Enum-Type being not type safe while the converse is true for the later).

And, in the following code, I further wonder what's the need to create instance of example, and what purpose does it solve, Because a gets 0 and b gets 1, in step (1) itself, then, whats the need to create instances

Edit: (Pls correct if wrong) The importance of creating instance is that, now, hello would only be able to take either a or b, it can't even take 0.

enum example {a, b} ; // create a type, example // (1)
example hello ; // create instance named hello, of type example // (2)

CodePudding user response:

Yes, both enum and enum class define new types (just like struct and class are used to define new types). And yes, enum is not type safe - you can compare two unrelated enums directly for example and enums implicitly convert to int. enum class on the other hand is type safe - you cannot compare unrelated types (unrelated enum classes) and there are no implicit conversions.

See also:

https://en.cppreference.com/w/cpp/language/enum

  • Related