I wrote a Chess engine in Java and I am porting it over to C++. I am new to C++.

The idea:

I have a Board object which holds a 2-dimensionnal array of Piece objects. Queen, Rook, Bishop, etc are subclasses of Piece. They all have a method getPossibleMoves(). Therefore they need to have a reference to the board to be able to generate the possible moves.

The implementation:

Board class:

class Board
    using PiecePtr = std::shared_ptr<Piece>;
    std::array<std::array<PiecePtr, BOARD_SIZE>, BOARD_SIZE> myPieces;

Piece class:

class Piece
    std::weak_ptr<Board> myBoard

I used shared_ptr and weak_ptr because the Board can/should exist whitout Pieces. Is this approach correct?

Note: I know this OOP approch to represent the chess board is not the best for performance. Other approaches (Bitboards for instance) will be more efficient.

closed as unclear what you're asking by BЈовић, GlenH7, jwenting, user40980, gnat Oct 4 '14 at 6:20

Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.

  • I have removed the constructors and methods in both classes for clarity. – Romain Sep 30 '14 at 12:25
  • Pieces without a board are useless. What do you mean with "they are way faster than my solution`? – BЈовић Sep 30 '14 at 12:27
  • 1
    @jwenting no, it is not. Optimizations are done at the end, when the bottle necks are identified. – BЈовић Sep 30 '14 at 12:55
  • 2
    @BЈовић no, when you identify a massive difference in potential performance during the design phase like this, or KNOW that one implementation will be far more efficient than another, you take the most efficient solution directly and save yourself a lot of work afterwards. Only fools implement something that they KNOW is bad and then afterwards try to change it around, chipping away at minor details, in order to try to get it to perform a fraction better when they could have prevented having to do all that work had they paid attention at the beginning. – jwenting Sep 30 '14 at 13:14
  • 1
    @jwenting I'd be inclined to agree, if your scope is to write a program meant to be used in production. If the scope is to learn, I think it is far more valuable to understand why one way is more efficient than another, hence you must crawl before you can walk. – Neil Sep 30 '14 at 15:40

This is a case of premature over-design.

The pieces don't need a pointer to the board. Just pass the board to the 'generateMoves' method. You don't even need objects for the individual chessmen. All pawns are alike, so you only need one Pawn instance.

Also, by the laws of chess, there is a game state that is also needed to correctly generate moves. Pawns can capture e.p. but only after a previous two-square advance. A king can castle with a rook but not if either has previously moved.

My suggestion is to forget all the class design stuff. Start with a single ChessGame class with two methods: generateMoves and makeMove. Write it test-first. Start by only having two kings on the board. Then add the different kinds of chessmen one at a time. Extract classes as you find it convenient.


A small "being there, done that" suggestion... migrating my chess engine from a 0x88 board representation to bitboard was relatively simple. Obtaining a performance improvement was way harder than I expected.

The fact is that you can have a wonderful design for your board/piece class, perfect modularity, minimum dependencies among classes... but it's sure that you must have arranged your evaluation logic depending on what you can do fast or slow (and this is linked to board representation).

Changing the board representation will trigger changes in the static evaluation logic: that's complex, time consuming and risky.

Moreover, while you change the evaluation logic, you discover that some search extensions aren't needed anymore or that you need a better quiescence search.

Eventually you could have a completely different player.

So you can start with a "temporary" board representation but everything should be done bearing in mind the final representation (strong/weak points of a representation you are not using could be unexpected).

Your implementation is the typical Team/Members relationship. The Team object (the board) will have pointers to its Members (the pieces) and the members will also have a back pointer to their Team object.

So weak_ptr is used to break the dependency cycle: the "owner" use shared_ptr and the "owned" use a weak_ptr to its parent and convert it temporarily to shared_ptr when it needs access to its parent.

So, from this point of view, it's a correct implementation.

However the getPossibleMoves() function will need the piece position to perform its task.

The function could find out the position scanning the board but this would slow down the move generation. To avoid data redundancy you shouldn't store the coordinates inside Piece and getPossibleMoves() will need two arguments:

std::list<Move> ThePiece::getPossibleMoves(unsigned row, unsigned column)
  // ...

// ...
Board b;
// ...
auto moves = b[row][column]->getPossibleMoves(row, column);

Now why not remove the myBoard injected dependency from Piece and add one more argument to getPossibleMoves?

std::list<Move> ThePiece::getPossibleMoves(const Board &b, unsigned row, unsigned column)
  // ...

After this change the shared_ptr aren‘t required anymore... along this way we‘re going to completely change the design.


Please review the background and use cases for weak_ptr. I don’t think this is one of them.

weak_ptr is typically used for as a cache. The owner of the weak_ptr must be ok with the weak_ptr being null. If the weak_ptr is null, the owner can adapt by constructing a new instance or otherwise operating differently.

In your case, a Piece cannot operate without a Board. The weak_ptr should be a smart_ptr.

I would go farther and say that you should not be using pointers at all. The entire system is well defined without any pointers. Try an entirely value based design. For example, the Board for the pieces could be a reference instead of a pointer.

  • 1
    weak_ptr isn't being used improperly. You might be confusing yourself with a weak pointer in Java, which only points to an object until the next garbage collection (and is therefore truly unstable). weak_ptr just means that it doesn't interfere with the destruction of referenced object if the owner destroys it. In this case, it is used to provide a reference, but not ownership of the board in each piece. – Neil Sep 30 '14 at 15:36
  • A weak_ptr is valid until the owning of the shared_ptr is deleted. If the board is deleted then the weak_ptr of Piece is no longer valid, i.e. the weak_ptr will fail to lock. That sounds like a cache to me. What would Piece do if the Board is deleted? – Bill Door Sep 30 '14 at 16:35
  • 2
    @BillDorr First of all: a shared ptr will cause circular dependencies that would lead to memory leak. Secondly, Pieces don't own the board so a shared pointer would express incorrect ownership. Technically, the piece could also store raw pointer, but then, if it somehow outlived the board it references, there would no way to detect that piece tries to reference incorrect pointer. – UldisK Oct 1 '14 at 4:36
  • +1 using references, might be better then using smart pointers in this case – BЈовић Oct 1 '14 at 7:48
  • @UldisK, the circular dependencies is a good point. On your second point, shared_ptr does not indicated ownership. That’s kind of the point of shared_ptr. shared_ptr often indicates lack of ownership. – Bill Door Oct 1 '14 at 15:42

Not the answer you're looking for? Browse other questions tagged or ask your own question.