0

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?

Tyler Gaona
  • 479
  • 1
  • 4
  • 14
  • `Piece(K,'K',color);` creates a temporary object. You need to use the mem-initializer-list. – dyp Jan 23 '14 at 23:18

1 Answers1

3

You have the wrong syntax (which is legal, but doesn't do what you think). You need to call the base class constructor in the initializaton list:

King(color_t color) : Piece(K,'K',color) {}

By the time you get into a constructor's body, all base classes and data members have already been initialized. If you don't initialize them explicitly, they get default initialized (which means calling the default constructor in the case fo the base class).

In your code, you were instantiating a local, anonymous Piece object.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480