I have a Carousel, which is composed of CarouselSections, which are in turn made up of CarouselItems. There are several subtypes of CarouselItems, each which have different behaviour.
I draw the Carousel by iterating through all CarouselSections and drawing them, and the draw() method on each CarouselSection iterates through all its CarouselItems and calls draw() on those.
I build up my Carousel by filling it with generic CarouselSections, and filling those up with specific subtypes of CarouselItem. However, when I draw, the CarouselItem->draw() call uses the base CarouselItem draw() method, rather than the subtypes version of it.
If I subtype CarouselSection, then I have to manually specify the subtype of the CarouselItem in each subtype of CarouselSection, which is clearly repetition.
Is there a design pattern that will help me here? Feel like I'm missing something obvious...
Hard to say what is going on there. This should work:
1 2 3 4 5 6 7 8 9 10 11
class CarouselItem
{
public:
virtualvoid draw() = 0;
};
class SomeCoolCarouselItem : public CarouselItem
{
public:
virtualvoid draw() { //Implementation here. }
};
The only time where the derived implementation would not be called would be during construction of carousel item object. After construction, the vtable is patched and should use the derived class' draw() method.
Polymorphism only works with pointers or references. Make sure your collection of carousel items use pointers or references. Pointers is far more flexible as references can only be set on construction.