Reputation: 103
My problem is the following:
I am creating a chess game in C++, and there is a base class Figure
that contains the functionality shared by all figures with a virtual function checkMove
that is redefined individually for each figure (as, naturally, each figure moves under different rules). The chess board is a two dimensional array of pointers to Figure
s (empty squares are simply null pointers).
The thing is, I would like to have the Queen
inherit the Rook
and Bishop
, as it is a mix of both for all intents and purposes, instead of writing its own needlessly long checkMove
override.
And then comes my problem: in the base Figure
class, there are the fundamental functions of defining which character the figure will be represented by in the console, which team it belongs to, etc. I would like the queen to only inherit one instance of these functions.
However, I would like the queen to inherit the checkMove
function twice - once from the Rook
, and once from the Bishop
, so as to simply call both in its own checkMove
version..
I tried some solutions, also played around with the Rook
and Bishop
inheriting the Figure
class virtually, however I can't seem to put the pieces together. I am new to the concept of polymorphism so I can't find proper logic to implement that functionality. What would be a good approach?
Upvotes: 3
Views: 180
Reputation: 11022
A Queen is not a Rook.
I would steer (far) away from inheritance here - the only reuse is only for the queen really.
A better design here would be something like the following (pseudocode):
struct Queen {
ValidMoves canMove(GameState state) {
ValidMoves res;
res.insert( canMoveAsRook(state) );
res.insert( canMoveAsBishop(state) );
return res;
}
};
Upvotes: 2
Reputation: 180145
Yes, there is.
But it's not directly obvious. You don't inherit Queen
from Rook
and Bishop
. Instead, you introduce a specific Move
base class. Now QueenMove
can inherit from RookMove
and BishopMove
. The Queen
piece simply is a Piece
type, whose constructor sets Piece::move
(a unique_ptr<Move>
) to QueenMove
.
Upvotes: 1