Search code examples
c++visual-c++abstract-classchess

Making a 2D array of children elements


I'm trying to create a chess engine, so I made a Board class (only showing the h file because the implementation is pretty straight forward):

class Board {
private:
    Piece* board[SIZE][SIZE];
    bool turn;
public:
    Board();
    Piece* getBoard() const;
    void printBoard() const;
};

The idea is to make a 2D array filled with different pieces. Obviously, I made a Piece class as well (a parent class to all other pieces):

class Piece {
protected:
    bool color;
    int PosX;
    int PosY;
public:
    Piece(const bool c, const int x, const int y);
    ~Piece();
    virtual int tryMove(int toX, int toY, Board &board) const = 0;
    virtual char toChar() const = 0;
}

I made an EmptyPiece class to try and initialize the array, but I just can't figure out how to fill the array with those pieces.

the h file for EmptyPiece:

class EmptyPiece : protected Piece {
public:
    EmptyPiece(const bool c, const int x, const int y);
    char toChar() const;
    int tryMove(int toX, int toY, Board& board) const;
};

and this is how I'm trying to initialize the array:

Board::Board()
{
    turn = true;
    for (int i = 0; i < SIZE; i++) {
        for (int j = 0; j < SIZE; j++) {
            board[i][j] = EmptyPiece(0, i, j);
        }
    }
}

which results in an error:

E0413   no suitable conversion function from "EmptyPiece" to "Piece *" exists

Solution

  • On the right side of the following statement:

    board[i][j] = EmptyPiece(0, i, j);
    

    EmptyPiece(0, i, j) created a temporary object with type EmptyPiece, which is also convertible to type Piece. But the left side requires a variable of type Piece*, i.e. a pointer to a Piece object. In general, you can't assign a variable of type T to another variable of type T*.

    You can fix it with the following version:

    board[i][j] = new EmptyPiece(0, i, j);
    

    But you need to remember to delete the objects you new'ed.