I am implementing a chess module as I learn C++. In the module I have (partially) implemented:
- a
Board
class (grid, pieces, move methods etc.) - enumerated types
Colour
(BLACK/WHITE) andRank
(KING, QUEEN, ..., PAWN)
and
- a
Piece
structure grouping colour and rank (BLACK KING,..., WHITE PAWN).
I am now deciding how to represent the contents of a square on the board (grid). A square must either contain a Piece
(BLACK KING), or nothing. Options considered:
create a
struct Square
containing two data members,{bool occupied ; Piece piece;}
, (possibly extending thePiece
class).MY OBJECTION: Solution seems a little too heavy-weight, and in the event that the square is not occupied then the
piece
member should be empty. I feel it may lead to exceptions being needed for some class methods, which should not be necessary.extending the enumeration of
Rank
orColour
to include an empty option.MY OBJECTION: Feels semantically inelegant, hacky and unnatural.
looking into other packages like
std::optional
MY OBJECTION: For coding style and simplicity, I'd like to avoid the use of extra machinery. Would
std::optional
even be suitable?using
NULL
ornullptr
to represent the state of an empty squareMY OBJECTION: Again, seems hacky. The contents of an empty square are NOT
NULL
, nor the number0
, should not be comparable to the number 26... but should be a fresh, new constant EMPTY_SQUARE.
None of these options quite seem to fit. Is there some more elegant way of extending a class (like Piece
) with other members (like EMPTY_SQUARE
) which has none of the original class's data members? (Are there any other options?)