What would be the right way to write an enum inside a class? I am writing conway's game of life code in c++. So i have a patterns class which contains the info about different kind of patterns:
class Patterns
{
public:
Patterns();
~Patterns(void);
private:
enum class PatternType
{
bloat,
block,
blinker,
toad
};
PatternType pattern_;
};
My goal is not to pollute the global space here. So is it the write way of writing the enum inside of a class keeping oops concepts in mind. If not, please suggest some better alternatives and what are their benefits over this method. Any inputs on keeping things in mind while writing enums inside of a class are welcome.
Edit: @Jay Miller Based on his inputs i have tried all of his three methods
enum class PatternClassOut{ point, circle, triangle };
class Patterns
{
public:
enum PatternSimple{bloat, block, blinker, toad};
enum class PatternClassIn{cat, mouse, dog};
//get set functions for all the enum variables
private:
PatternClassOut out_;
PatternSimple simple_;
PatternClassIn in_;
};
My findings (After trying out the code & googling a bit):
- PatternSimple is the simplest way to write the enum in my case, inside of the class; but it compromises on type safety i.e i can compare the enum values with any other data type and it wont give any error.
- PatternClassIn provides type safety; but i have to write more code in the calling funcion, to access the enum values.
- PatternClassOut provides the best of both worlds. It provides type safety, moreover, the code from the calling function to access enum values is same as that of PatternSimple.
Assuming you want this to be available outside your class, making the enum public makes sense. As an
enum class
, you will need the enum name to access the values in addition to the class name:Because it is an enum class, it may be perfectly valid to move it outside of another class. The only addition to the global namespace will be the name of the enum.
If you have other operations you want to group with the enum then nesting it in a class as you have makes sense. You may decide, in that case, to just use
enum
rather thanenum class
: