0

I couldn't come up with a self-explanatory and short title, here is my problem. I have a base class(Piece) and derived class(Pawn). In order to create Piece objects, I call the constructor of derived class with parameters. It is working fine. But now, I'm defining another class whose name is Board, and this class will have array of Piece objects. The problem is, I want to create a single Board object and don't know how to initialize Base class objects properly in it. Because I used to initialize base class objects using derived class constructor but now I don't have that option. How am I going to write the constructor of Board class?

class Piece {
public:
    Coordinates coor;
    whose color;                                 
    Piece(Coordinates a, enum whose c, char n); 
};

class Pawn : public Piece {
public:
    Pawn(Coordinates a, enum whose c, char n) :Piece(a, c, n){}
};

class Board {
private:
    Piece node[32]; 

public:
    Board(); //How to write the constructor? 
    void show_board();

};

3
  • I don't think a Board is a matrix of Pieces - if anything, its a matrix of Squares. Also, why 9x9? Commented Sep 8, 2019 at 11:25
  • @NeilButterworth You're right. My bad. I should have created matrix of squares. Anyway, I still want to create 32 Piece objects in a single Board object. Question stays same :) I edited the question, instead of matrix, now there is a one dimensional array with 32 elements. And 9x9 is just a preference, there are some unused bits. Maybe I'll change this in the future. Commented Sep 8, 2019 at 11:39
  • stackoverflow.com/q/8462895/1216776 Commented Sep 8, 2019 at 11:43

1 Answer 1

1

First, you must not declare an array of base type objects if you are going to store derived objects. You will end up having Object Slicing.

To solve that you need to store an array of pointers to base class object :

Piece *board[9][9]; 

And initialize it in the constructor, for instance:

Board::Board() : board() // this initializes all slots of "board" to nullptr.
{
   // create new Piece or derived objects in the array slots you want
   board[4][2] = new Pawn(x1, y1, z1);
   board[7][0] = new Pawn(x2, y2, z2);
   ...
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.