Suppose I am implementing a game of two-player chess. Here is a shortened version of my implementation for simplicity's sake, omitting any irrelevant details. I have a class Piece from which the various pieces are derived. In this example I am only including the King piece.
extern enum piece_t;
extern enum color_t;
class Piece
{
public:
Piece() {}
Piece(piece_t t, char r, color_t c)
: type(t), representation(r), color(white)
{}
char getRepresentation()
{ return representation; }
protected:
piece_t type;
color_t color;
char representation;
};
class King : public Piece
{
public:
King() {}
King(color_t color) { Piece(K,'K',color); }
};
In another class, Board I define a member to instantiate King
class Board
{
public:
Board() { king = King(white); }
friend ostream& operator<<(ostream&, const Board&);
private:
King king;
};
Here is an example of main:
int main(void)
{
Board game;
std::cout << game;
return 0;
}
The problem is that the default constructor is being called. I know this is happening because my king object is being initialized with garbage.
My intention is for king to be initialized in Board's constructor:
Board() { king = King(white); }
From here I want the constructor from King which takes a color_t argument to be called, which will thereby call the constructor from Piece like so:
King(color_t color) { Piece(K, 'K', color); }
This is not what is happening. The default constructor (of either King or Piece or both) is being called. Is king's default constructor called when it is declared in the private field of Board? If this is the case, how do I alter the code so that king calls the appropriate constructor?