Search code examples
c++stlshared-ptr

How to use multi-inheritence with std::shared_ptr?


So, I have code like this:

class IUpdatable {
    virtual void onUpdate() = 0;
};
class IDrawable {
    virtual void onDraw() = 0;
};
class IEventable {
    virtual void onEvent() = 0;
};

class IObject {};
class Button : public IObject, public IUpdatable, public IDrawable, public IEventable {/*override of virtual metothods*/};
class NonVisibleButton : public IObject, public IUpdatable, public IEventable {/*override of virtual methods*/}

int main(){
    std::vector <std::shared_ptr <IObject>> buttons = {
        new Button(),
        new NonVisibleButton()
    };
    std::vector <std::weak_ptr <IEventable>> eventables = {
        buttons.at(0),
        buttons.at(1)
    };
    std::vector <std::weak_ptr <IDrawble>> drawbles = {
        buttons.at(0)
    };
}

So, can I realize this and how? I want to regulary update vector with buttons in the different containers. (to be more precise, I have individual thread for updating IEventable's child class' objects and absolutely everything that inherits from IEventable goes here)


Solution

  • Something like this could work:

    #include <vector>
    #include <memory>
    
    class IUpdatable {
    public:
        virtual void onUpdate() = 0;
    };
    class IDrawable {
    public:
        virtual void onDraw() = 0;
    };
    class IEventable {
    public:
        virtual void onEvent() = 0;
    };
    
    class IObject {
    public:
        virtual ~IObject() = default;
    };
    
    class Button : public IObject, public IUpdatable, public IDrawable, public IEventable {
    public:
        void onUpdate() override {}
        void onDraw() override {}
        void onEvent() override {}
    };
    
    class NonVisibleButton : public IObject, public IUpdatable, public IEventable {
    public:
        void onUpdate() override {}
        void onEvent() override {}
    };
    
    int main(){
        std::vector <std::shared_ptr <IObject>> buttons = {
            std::static_pointer_cast<IObject>(std::make_shared<Button>()),
            std::static_pointer_cast<IObject>(std::make_shared<NonVisibleButton>())
        };
        std::vector <std::weak_ptr <IEventable>> eventables = {
            std::dynamic_pointer_cast<IEventable>(buttons.at(0)),
            std::dynamic_pointer_cast<IEventable>(buttons.at(1))
        };
        std::vector <std::weak_ptr <IDrawable>> drawbles = {
            std::dynamic_pointer_cast<IDrawable>(buttons.at(0))
        };
    }
    
    

    Honestly though, I wouldn't try to shoehorn a Java code structure (interfaces, inheritance, etc) into C++... Try composition over inheritance if possible.