1
enum Color1 { red, blue, green }; // ok
// enum Color2 { red, blue, green }; // error, enum conflicts

struct Color3
{
    enum { red, blue, green }; // ok, no conflicts
};

enum class Color4 { red, blue, green }; // ok, no conflicts
  1. Color1 and Color2 are both weak typing.
  2. Color3 and Color4 are both strong typing.

My questions are:

1. Is there any difference between Color3 and Color4?

2. Which to prefer? Color3 or Color4? Why?

xmllmx
  • 39,765
  • 26
  • 162
  • 323
  • For `Color1`, the outer class doesn't really matter, `red` is just a plain `enum`. So you are really asking about the difference between an `enum` and an `enum class`, and yes, there are differences between them. Both ways work, so I'm voting to close this as opinion-based, unless you make it more focused about a real technical issue. – Remy Lebeau Apr 02 '21 at 15:20
  • About the strong typing, try `std::cout << 42 + Color1::red << '\n';` and then with `Color2::red`. Related: https://stackoverflow.com/questions/18335861/why-is-enum-class-preferred-over-plain-enum – Bob__ Apr 02 '21 at 15:24

1 Answers1

4

Color3 and Color4 are both strong typing

No. Try this:

int x = Color3::red; // ok
int y = Color4::red; // error: cannot convert from 'Color4' to 'int'

The legacy enum is implicitly convertible to an integer, but enum class is it's own type.

As to which to prefer, refer to Why is enum class preferred over plain enum?

rustyx
  • 80,671
  • 25
  • 200
  • 267