Search code examples
c++oopinheritancechess

Chess piece hierarchy design: inheritance vs type fields


I have a base class for pieces

 class piece;

and an array containing derived objects

piece* board[8][8];

Advantage, clean design through virtual functions. Disadvantage, if I have to find a piece in the board or compare a piece I have to revert to dynamic casting (or typeid). It’s ugly and could be a performance hog when making millions of requests.

In the other hand, if I make an array of a single piece class, that has a type field for identifying pieces, I don’t have this problem (and it should be faster) but I have to make super ugly switch statements. I guess that since the number of pieces is finite and I don’t see myself making that many of switches, this could be in the end a better choice, what do you think?

This is for fun (so no bitboard).

Reading some answers, I think using type fields only for operator overloading (==, !=, ...) could bring the best of both words.

The boost::variant looks very interesting too.


Solution

  • I would go with the class hierarchy.

    For finding a piece you can keep a separeted list for each piece type. So you know where to look for each piece type.

    For comparison you can rely on virtual methods too.

    Another aproach is to use a component architecture (like described here: http://cowboyprogramming.com/2007/01/05/evolve-your-heirachy/), but I think it is too much for a chess game where you clealy know the types and know that those types will not change soon :).