K.Yazoglu
K.Yazoglu

Reputation: 317

How to initialize base class objects which are member variable of another class?

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();

};

Upvotes: 0

Views: 89

Answers (1)

Redgis
Redgis

Reputation: 79

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);
   ...
}

Upvotes: 1

Related Questions