I was planning on making a 2d chessboard game using classes and other OOP techniques. I know a little on polymorphism and was wondering if the technique used in polymorphism whereby I can delegate duties to the children class from the base class is applicable via composition.
[Edited] A chessboard has players.I want to polymorphically call method functions move defined in both players without having to say player1.move(), player2.move()
Don't get lost in design patterns or design techniques. This question seems like an XY problem. Always take a step back and consider what you want to achieve.
A single call to ask both players to move.
If there is no other context, I'd say just call them!
In general:
So what's wrong a chess flow controller to call two players to move in fixed order?
What would you gain from applying polymorphism to replace following code?
void begin_round(){
player1.move();
player2.move();
}
You'd save two line of type by calling a move... Hey wait! That's what begin_round()
does!
Polymorphism approach does not save anything but increase complexity of the system which is a bad sign for system design.
Most of time, an as stupid as possible design is better than a complex approach, unless the design would save a lot of maintaining or developing resource. If a design saves nothing, then don't use it until it's a must.
Composition is quite common in your case since a game
is a composition for a board and two players.