0

I'm making a chess game, and I'm laying out the classes. It makes sense to have a base Piece class, and separate Rook, Bishop, Knight, Pawn, King, and Queen classes to inherit from it. The only parameter the constructor will need is a boolean "owner" value (which will be a member of the base class): true for player, false for AI. I think the objects should be instantiated like this:

//create a Rook owned by the player
Rook exampleRook = new Rook(true);
//create a Knight owned by the AI
Knight exampleKnight = new Knight(false);

It seems like I would have to do something like this in each derived class:

Rook(bool owner) {
    this->owner = owner;
}

Which seems to violate the whole principle of inheritance: write code once in the base class, and then inherit. I might have to write a setOwner() function in the base class, but it seems to make more sense to set the owner in the constructor instead of in a separate function (which could be called again).

qxu21
  • 518
  • 5
  • 11

1 Answers1

5

You can put the member initialization in the base class constructor's initialization list

Piece(bool _owner) : owner(_owner) {}

Then in the derived classes just pass through to the base class constructor

Rook(bool owner) : Piece(owner) {}
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218