Painting a Component through a custom base class

I’m creating a family of Component objects that I want to act polymorphicly, so I create a base class for them. The Base class itself is a Component, so that it can be added to Component hierarchy. This all compiles, but the derived Component never has its paint() method called.

class MyBase : public Component
{};

class MySlider: public MyBase, public Slider
{};


class MainContentComponent : public Component
{
public:
    std::unique_ptr<MyBase> slider;
  
    MainContentComponent()
    {
        slider.reset(new MySlider());
        addAndMakeVisible(*slider);
        slider->setBounds(30, 30, 400, 100);
        setBounds(0, 0, 600, 600);
    }
};
 // This code compiles, but the slider is never displayed.

How can I modify this code so that the paint() method of the correct derived class is called?

The code I’ve posted probably looks a bit suspicious, so let me add a few comments:

  1. MyBase looks obsolete, but this is because I’ve omitted some details that are irrelevant to the question. In reality this class will have a lot of work to do, so I’d really like to hold on to it.

  2. I am aware of the ambiguity of MySlider inheriting from Component twice. I was part expecting the code not to compile because of the diamond problem. It does compile, but I still suspect that the problem is due to this ambiguity.

It’s not a good idea to derive from two Component based classes. If your purpose is to combine Component derived classes and custom functionality, this might do it:

class MyBase 
{
public:
  Component &component;

  MyBase(Component &c) : component(c) {}

  void repaint() { component.repaint(); }
  Component &getComponent() { return component; }
};

class MySlider: public Slider, public MyBase
{
public:
  MySlider() : Slider(), MyBase(*this) { }
};

class MainContentComponent : public Component
{
public:
    std::unique_ptr<MyBase> slider;
  
    MainContentComponent()
    {
        slider.reset(new MySlider());
        addAndMakeVisible(slider->getComponent());
        slider->getComponent().setBounds(30, 30, 400, 100);
        setBounds(0, 0, 600, 600);
    }
};

That’s perfectly clear–thanks for the suggestion. Prefer composition over inheritance!

I have been working on a project that I have restarted numerous times. At one point I was about to go down this path. I couldn’t find my old files, but I found an example off the net that might be useful for you to explore, but using components and sliders.
Cheers

```
 namespace a
{
 class A1 {
 public:
    void testA1() {...}
};
}

 namespace b
{
 class B1: public class a::A1
{
  public:
     void testB1()
        {
           a::A1::testA1();
          ...
        }
};
}
 ```