I am implementing a chess module as I learn C++. In the module I have (partially) implemented:
- a
Boardclass (grid, pieces, move methods etc.) - enumerated types
Colour(BLACK/WHITE) andRank(KING, QUEEN, ..., PAWN)
and
- a
Piecestructure 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 Squarecontaining two data members,{bool occupied ; Piece piece;}, (possibly extending thePiececlass).MY OBJECTION: Solution seems a little too heavy-weight, and in the event that the square is not occupied then the
piecemember 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
RankorColourto include an empty option.MY OBJECTION: Feels semantically inelegant, hacky and unnatural.
looking into other packages like
std::optionalMY OBJECTION: For coding style and simplicity, I'd like to avoid the use of extra machinery. Would
std::optionaleven be suitable?using
NULLornullptrto 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?)