Search code examples
c++staticconstantsdeclaration

C++ Java static final equivalent


I am using C++ to program a chess game. I want to create two class attributes for the class Board: ROWS and COLUMNS. In Java, I would declare they as static final and everything would work as I want. How I do the same declaration in C++? I need to access these attributes by "Board::ROWS" and "Board::COLUMNS" in other classes.

What I have is this, which is throwing compilation errors since ROWS and COLUMNS are not declared in the scope of the declaration of m_TileMap. Is there a good practice for doing this without using #define statement?

class Board {
  Tile *m_TileMap[ROWS][COLUMNS];

public:
  static const int ROWS = 8;
  static const int COLUMNS = 8;

  Board(int m[ROWS][COLUMNS]);
}

Solution

  • declare your m_TileMap after the declaration of ROWS and COLUMNS

    e.g.

    class Board {
    
    public:
      static const int ROWS = 8;
      static const int COLUMNS = 8;
    
      Board(int m[ROWS][COLUMNS]);
    
    private:
      Tile *m_TileMap[ROWS][COLUMNS];
    };
    

    The reason for this is because in C++, the compiler does not read forward. So in order for ROWS and COLUMNS to be understood by the compiler when you declare m_TileMap, they need to be declared before.