3

By using normal enum it was a good practice to use explicit values to avoid unintentional inserting in the middle of an enum. It was quite essential since the enum items could be implicitly cast to integer.

What about enum class? Is it still a good practice to set explicit values or this is just an "outdated" behaviour?

E.g.:

enum class Animal
{
    Dog = 0,
    Cat = 1
};
Tibor Takács
  • 3,535
  • 1
  • 20
  • 23
  • 1
    I'd say the readability is what should really matter here. If you need the values to be specific, or for some reason you don't want these values to change between versions of your software, use explicit values. If you need "just value", use implicit as it expresses your intent in a more clear way. – alexeykuzmin0 Mar 28 '18 at 09:50
  • Nothing wrong with setting explicit values: in some cases it's the only way to get desired behavior. See this about `enum` vs. `enum class`es: https://stackoverflow.com/questions/18335861/why-is-enum-class-preferred-over-plain-enum – JHBonarius Mar 28 '18 at 09:51

3 Answers3

1

If I understand your question correctly, you are referring to binary compatibility. In the olden days when you couldn't forward declare an enum, you'd see something like this:

//Some header
enum Animal
{
    AnimalDog = 0,
    AnimalCat = 1
};

// Some other header, not #including the previous one    
void func(int an_animal); // Accepts an Aninal enum

And of course, if the enum was changed, then for the interest of binary compatibility, it was damn important to add the new enumerator at the end of the enumeration.

Does it change with scoped enums? Well, yes and no. You can foward declare a scoped enumeration.

//Some header
enum class Animal
{
    Dog = 0,
    Cat = 1
};

// Some other header, not #including the previous one    
enum class Animal;
void func(Animal);

So now you have some added type safety and scoping to avoid namespace pollution. But the same considerations about binary compatibility apply.

So I'd say yes. Keep doing what you are doing with scoped enumerations too.

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
1

There's no need, in your posted snippet, to give explicit values to the enumerants, whether it's an enum or an enum class. It's potentially unsafe to give only some of the enumerants explicit values, but it's safe to give none of them values.

The MISRA C++ guidelines, by way of example, recommend that either all or none of the enumerants be given explicit values, but even that is fairly restrictive, and there are reasonable and safe use cases for only giving values to only some enumerants.

None of this differs between enum and enum class. The things that would be safe in one are safe in the other.

Sneftel
  • 40,271
  • 12
  • 71
  • 104
0

It is the same as enum class only adds type safety and locality (you need to use qualified names) of its values.

Yola
  • 18,496
  • 11
  • 65
  • 106