user1066113
user1066113

Reputation: 939

Where to define enums

Say I want to create a card class. and want to have enums for the cards

2,3,4,5,6,7,8,9,J,Q,K,A

Where's the best place to define this, the header file Card.h or Card.cpp?

Upvotes: 10

Views: 12300

Answers (4)

Parag Amritkar
Parag Amritkar

Reputation: 111

The best way to define the enum is to declare it in header file. So, that you can use it anywhere you want by including that header file during compilation.

Upvotes: 0

Bukes
Bukes

Reputation: 3718

How about something like this:

class CCard
{
public:
    CCard( void );
    virtual ~CCard( void );

    // Card face type
    enum eCardFaceType
    {
       Face_2,
       Face_3,
       Face_4,
       Face_5,
       Face_6,
       Face_7,
       Face_8,
       Face_9,
       Face_10,
       Face_Jack,
       Face_Queen,
       Face_King
     };

     // Card suit
     enum eSuitType
     {
         Suit_Clubs,
         Suit_Diamonds,
         Suit_Hearts,
         Suit_Spades
     };

    // Internal data.
protected:
     eCardFaceType m_face;
     eSuitType  m_Suit;
};

Upvotes: 0

Gerald
Gerald

Reputation: 23499

I would do it like this, in the definition of your card class:

class Card
{
public:
   typedef enum
   {
      Two = 0,
      Three,
      Four,
      Five,
      Six,
      Seven,
      Eight,
      Nine,
      Ten,
      Jack,
      Queen,
      King,
      Ace
   } Face;
};

Or C++11:

class Card
{
public:
   enum Face: unsigned char
   { 
      Two = 0,
      Three,
      Four,
      Five,
      Six,
      Seven,
      Eight,
      Nine,
      Ten,
      Jack,
      Queen,
      King,
      Ace
   };
};

Upvotes: 4

Pablo Santa Cruz
Pablo Santa Cruz

Reputation: 181460

It's going to be a new type. So I would probably put it on the header file in case I need it in other compilation units.

Upvotes: 5

Related Questions