3

I'm probably missing something but I'm working with a code base that uses a lot of

typedef enum foo
{
    ....
} foo;

Is this just the same as an enum class but not strongly typed?

cigien
  • 57,834
  • 11
  • 73
  • 112
Joshua Williams
  • 155
  • 1
  • 7
  • No, this is a regular enum. This `typedef` does nothing useful in C++ (but did something useful in C) – UnholySheep Jul 03 '20 at 22:39
  • See https://stackoverflow.com/questions/18335861/why-is-enum-class-preferred-over-plain-enum It should answer your question. – cigien Jul 03 '20 at 22:39
  • Does this answer your question? [Why is enum class preferred over plain enum?](https://stackoverflow.com/questions/18335861/why-is-enum-class-preferred-over-plain-enum) – Adrian Mole Jul 03 '20 at 22:51

1 Answers1

8

Using typedef enum does something different than enum class.

The use of typedef enum, as @UnholySheep mentioned in the comments, is mostly a C idiom that isn't needed in C++. In C, if you declared an enum like this:

enum Ghost {
    Blinky,
    Pinky,
    Inky,
    Clyde
};

then to declare a variable of type Ghost, you'd have to say

enum Ghost oneGhost;

The use of "enum" here could be a bit annoying, so a pattern emerged of writing out the enum declaration as

typedef enum Ghost {
    Blinky,
    Winky,
    Pinky,
    Clyde
} Ghost;

This says "there's a type called enum Ghost defined as usual, but you can just call it Ghost for short. That way, in C, you could write

Ghost myGhost;

and have everything you need.

However, C++ dropped the requirement to use enum this way. If you have a Ghost defined using the first (typedef-free) version of the code, you could just say Ghost myGhost; just fine. In that sense, there's not much reason to use typedef enum in C++.

This is quite different than enum class. In C++, enum class has the advantage that the constants defined in the enumeration don't end up as part of the namespace in which the enum was defined, and you can't implicitly convert from an enum class to an integer type. In that sense, enum class is mostly about type safety and making it hard to make mistakes with an enum.

Hope this helps!

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065