Class hierarchy problems

Hi,

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:
    virtual void draw() = 0;
};

class SomeCoolCarouselItem : public CarouselItem
{
public:
    virtual void 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.

Do you have a similar set up?
Did you forget to make draw a virtual function?
I have the virtual keyword in front of both the superclass class and sub class function declarations in the corresponding header files.

I provided an implementation of the superclass class's draw function, which I am calling in the sub classes implementation.

Stumped..
How are the CarouselItems stored? As pointers?
The CarouselSections are stored as pointers, and the CarouselItems as objects.
However, when I draw, the CarouselItem->draw() call uses the base CarouselItem draw() method, rather than the subtypes version of it.


I provided an implementation of the superclass class's draw function, which I am calling in the sub classes implementation.


So, in other words, you're getting exactly the behavior you specified?
Last edited on
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.
Except the subclass's implementation does more afterwards... which is not getting done.
Ah okay, thanks everyone.
Topic archived. No new replies allowed.