Search code examples
c++coding-styleenums

Namespace level enums in c++


Is it a bad practice to have enums in c++ directly at namespace level? I mean not associated with any class? Say if I have an enum and a class that looks something like this,

enum Player { USER, COMPUTER}

class Game {
//Logic of the game.
};

So should I be declaring the Player enum as a member of game class? Should it be private?


Solution

  • With C++11

    This answer was originally written in 2011. Now that C++11 support is widely available, the preferred way is to use enum class, as Matthew D. Scholefield points out below:

    enum class Player {
        User,
        Computer
    };
    

    The enumerated constants must be qualified with the name of the enum when referenced (e.g., Player::Computer).

    Before C++11

    No, there's nothing inherently wrong with an enum being public. Bear in mind, however, that enumerated constants cannot be qualified with the name of the enclosing enum type. That is, you cannot write Player::USER or similar to refer to the USER constant; they appear directly in the enclosing namespace. As such, it might be a good idea to set a prefix for your constants so that no name collisions occur.

    For instance, consider the following declaration:

    enum Player {
      PL_USER,
      PL_COMPUTER
    }
    

    This is safer, because name collisions are much less likely with the "PL_" prefix. Additionally, it improves code readability by hinting at which enum a given constant belongs to.

    Languages like C# and Java have adopted a slightly different approach to enums, where one has to specify both the name of the enumeration and the name of the constant, such as Player.USER. A similar effect can be achieved in C++ by embedding the enum declaration within a namespace of its own. For example:

    namespace Player {
      enum Type {
        USER,
        COMPUTER
      }
    }
    

    This has the effect of embedding PLAYER and COMPUTER in the Player namespace instead of the global (or otherwise enclosing) namespace. Whether this is a good approach or not is, in my opinion, a matter of preference.