Use inheritance only for polymorphism in c++ -
i´m designing project in c++ , got point i´m in doubt whereas should use inheritance have polymorphism.
specifically, have class jazzquartet has 4 objects: saxophonist, pianist, bassist , drummer, each play() , listen() methods, different implementations.
i´d make them inherit class musician can have array of musician objects , call each one´s play() , listen() methods, , can make musician listen() other. implementation different each other, i´d using heritage polymorphism, , i´m not sure if that´s design choice.
any advice on matter?
thank in advance!
"... can have array of musician objects , call each one´s play() , listen() methods, , can make musician listen() other."
musician should abstract class, i.e. interface:
class musician { public: virtual void play() = 0; virtual void listen(musician& other) = 0; virtual bool isplaying() = 0; virtual ~musician() {} }; and yes it's considered design promote interfaces.
this way enforce derived classes must implement these functions, , allow clients access musician instances, without need know concrete derived type.
as you've been asking store whole ensemble array:
with above design can use array of std::unique_ptr<musician> aggregate particular ensemble of musicians.
std::vector<std::unique_ptr<musician>> jazzquartet(4); std::unique_ptr<saxophonist> sax = new saxophonist(); std::unique_ptr<pianist> piano = new pianist(); std::unique_ptr<bassist> bass = new bassist(); std::unique_ptr<drummer> drums = new drummer(); jazzquartet[0] = sax; jazzquartet[1] = piano; jazzquartet[2] = bass; jazzquartet[3] = drums; // , wire them necessary //------------------------------------ // in combo needs listen drums sax->listen(*drums); piano->listen(*drums); bass->listen(*drums); ... // let them play for(auto& m : jazzquartet) { // note & avoid copies made items m->play(); }
Comments
Post a Comment