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]);
}
The static keyword means the value is the same for every instance of the class. The final keyword means once the variable is assigned a value it can never be changed. The combination of static final in Java is how to create a constant value.
The static data members are basically same in Java and C++. The static data members are the property of the class, and it is shared to all of the objects.
Java final is equivalent to C++ const on primitive value types. With Java reference types, the final keyword is equivalent to a const pointer...
Declaring variables only as static can lead to change in their values by one or more instances of a class in which it is declared. Declaring them as static final will help you to create a CONSTANT. Only one copy of variable exists which can't be reinitialize.
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.
You can re-order the class members, so that ROWS and COLUMNS are declared before they're used:
class Board {
public:
static const int ROWS = 8;
static const int COLUMNS = 8;
Board(int m[ROWS][COLUMNS]);
private:
Tile *m_TileMap[ROWS][COLUMNS];
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With