Question

I always read that composition is to be preferred over inheritance. A blog post on unlike kinds, for example, advocates using composition over inheritance, but I can't see how polymorphism is achieved.

But I have a feeling that when people say prefer composition, they really mean prefer a combination of composition and interface implementation. How are you going to get polymorphism without inheritance?

Here is a concrete example where I use inheritance. How would this be changed to use composition, and what would I gain?

Class Shape
{
    string name;
  public:
    void getName();
    virtual void draw()=0;
}

Class Circle: public Shape
{
    void draw(/*draw circle*/);
}

No correct solution

Licensed under: CC-BY-SA with attribution
scroll top