Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]);
}
like image 278
Lucas Kreutz Avatar asked May 17 '13 17:05

Lucas Kreutz


People also ask

Is static and final same in Java?

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.

Is static is same in Java and C?

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.

Is Java final same as C++ const?

Java final is equivalent to C++ const on primitive value types. With Java reference types, the final keyword is equivalent to a const pointer...

Can we declare static variable as final in Java?

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.


2 Answers

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.

like image 145
Jimmy Lu Avatar answered Nov 04 '22 05:11

Jimmy Lu


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];
};
like image 20
Andy Thomas Avatar answered Nov 04 '22 04:11

Andy Thomas