Search code examples
ooppolymorphismcomposition

Can polymorpism be applied to composition in c++?


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


Solution

  • Preface

    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.

    Target

    A single call to ask both players to move.

    TL;DR

    If there is no other context, I'd say just call them!

    Explanation

    In general:

    • A chess board always have two players. ( unless you're designing a specialized rule )
    • A chess flow is always operated in round robin ( first, then second, and then repeat ).

    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.

    Others

    Composition is quite common in your case since a game is a composition for a board and two players.