Search code examples
c++vectormultiple-inheritance

Store object with double inheritance in vector in C++


Let's say I got the following code:

#include <string>
#include <iostream>
#include <vector>

struct AddColorToText
{
    void MakeItRed(std::string text);
    void MakeItGreen(std::string text);
    void MakeItBlue(std::string text);
};

So the first struct is a general struct that can add color to any text I throw in. It's just an example; the idea is that the first struct contain methods and then I got another struct with complementary methods:

struct AddEffects
{
    void MakeItFlash();
    void MakeItFadeGradually();
    void MakeItBounce();
};

And finally I got this third struct that inherit from the first and second struct and provides even more methods:

struct SuperText: public AddColorToText, public AddEffects
{
    void SetSize();
    void SetFont();
}

Now imagine that for some reason I must store a superText object in a vector of AddColorToText pointers:

SuperText TheSuperTextObject;
std::vector<AddColorToText*> TheVector;

TheVector.push_back(&TheSuperTextObject);

What is the best/cleanest way to get back the SuperText methods from the AddColorToText pointers vector?

TheVector[0]->SetSize??????

Solution

  • Edit your class declaration to enable polymorphism like so:

    struct AddColorToText
    {
        void MakeItRed(std::string text);
        void MakeItGreen(std::string text);
        void MakeItBlue(std::string text);
        virtual ~AddColorToText() {}
    };
    

    As correctly pointed out in the comments, you need at least one virtual method for polymorphism.

    Then you could write

    SuperText *sup = dynamic_cast<SuperText*>(TheVector[0]);
    sup->SetSize();