Lesswire
Lesswire

Reputation: 859

Initializing an enum like if it where a class for avoiding a cast

Today I found some syntax that I haven't seen before.

enum MyEnum{    FOO = 0,    ABA,    DADA, }
....

MyEnum test;
std::uint8_t some_number(3);

test = MyEnum(some_number);

What exactly happens here? the enum will be treated like a class? or is this only a cast?

Upvotes: 1

Views: 90

Answers (2)

vinod
vinod

Reputation: 132

test = MyEnum(some_number);

Here the some_number is explicitly converting to enum type. The result of such a conversion is undefined unless the value is within the range of the enumeration.

Upvotes: 3

Enigma
Enigma

Reputation: 1717

MyEnum is declared as having three values:

FOO: 0
ABA: 1
DADA: 2

std::uint8_t some_number is initialized to the value 3. This value is than cast to a MyEnum value. Because there exists no mapping from value 3 to a MyEnum value, you probably get an undefined Enum value in test

Upvotes: 0

Related Questions