A quick search of this stackexchange shows that in general composition is generally considered more flexible than inheritance but as always it depends on the project etc and there are times when inheritance is the better choice. I want to make a 3D chess game where each piece has a mesh, possibly different animations and so on. In this concrete example it seems like you could argue a case for both approaches am I wrong?
Inheritance would look something like this (with proper constructor etc)
class BasePiece
{
virtual Squares GetValidMoveSquares() = 0;
Mesh* mesh;
// Other fields
}
class Pawn : public BasePiece
{
Squares GetValidMoveSquares() override;
}
which certainly obeys the "is-a" principle whereas composition would look something like this
class MovementComponent
{
virtual Squares GetValidMoveSquares() = 0;
}
class PawnMovementComponent
{
Squares GetValidMoveSquares() override;
}
enum class Type
{
PAWN,
BISHOP, //etc
}
class Piece
{
MovementComponent* movementComponent;
MeshComponent* mesh;
Type type;
// Other fields
}
Is it more a matter of personal preference or is one approach clearly a smarter choice than the other here?
EDIT: I think I learned something from every answer so I feel bad for only picking one. My final solution will take inspiration from several of the posts here (still working on it). Thanks to everyone who took the time to answer.
var Pawn = new Piece(howIMove, howITake, whatILookLike)
seems much simpler, more manageable and more maintainable to me than an inheritance hierarchy.