Home > Software engineering >  Accessing Enum defined within a class C
Accessing Enum defined within a class C

Time:06-04

I have the following code:

// Piece.h
class Piece 
{

  public:
    enum class Color {BLACK, WHITE};

    Piece();
    Piece(int x, int y, Piece::Color color);
    

  private:
    int m_x;
    int m_y;
    Piece::Color m_color;
    static const int UNINITIALIZED = -1;

};

How do I access the enum from the method functions: (attempt)

// Piece.cpp
Piece::Piece() :
  m_x(Piece::UNINITIALIZED),
  m_y(Piece::UNINITIALIZED),
  m_color(Piece::Color BLACK) // PROBLEM
{}

Piece::Piece(int x, int y, Piece::Color color) :
  m_x(x),
  m_y(y),
  m_color(color)
{}

The Problem:

Piece.cpp: In constructor ‘Piece::Piece()’:
Piece.cpp:8:24: error: expected primary-expression before ‘BLACK’
    8 |   m_color(Piece::Color BLACK)

I'm new to C so this might not be good code practice, but I would generally like to know how to achieve this (and also understand why I shouldn't write like this, if it is in fact bad practice)

Thank you

CodePudding user response:

You access enum (class) members like you would access any static member. Piece::Color::BLACK in this case.


In the constructor, you could omit the "Piece" part and just write the following:

Piece::Piece() :
  m_x(UNINITIALIZED),
  m_y(UNINITIALIZED),
  m_color(Color::BLACK)
{}

Regarding your hint about this being bad practice: It isn't. You could probably change the int to be a constexpr instead of just const, but whatever you are trying to do with the enum value is totally fine.

  • Related