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?

Related posts

Recent Viewed