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

2
  • 4
    Your code looks like Java. Are you sure it is C++? If it is, search for "inheriting constructors". Commented Aug 23, 2016 at 22:03
  • 1. Inheriting constructors, 2. Member initializer lists Commented Aug 23, 2016 at 22:03

1 Answer 1

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) {} 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.