Search code examples
c++inheritancevectormultiple-inheritance

C++ a way to get all inherited classes info


So i have this part of code

class Robot
{
    public: string Name;
    public: explicit Robot(const string& Name) { this->Name = Name; }
    public: Robot() { Name = "Robotic"; }
    public: virtual ~Robot() = default;
    public: virtual vector<string> GetCapabilities() = 0;
    public: friend ostream& operator << (ostream&, const Robot&);
};

class TalkingRobot : virtual public Robot
{
    public: explicit TalkingRobot(const string& Name) { this->Name = Name; }
    public: virtual ~TalkingRobot() = default;
    public: vector<string> GetCapabilities() { return { "Talking" }; }
};

class WalkingRobot : virtual public Robot
{
    public: explicit WalkingRobot(const string& Name) { this->Name = Name; }
    public: virtual ~WalkingRobot() = default;
    public: vector<string> GetCapabilities() { return { "Walking" }; }
};

class VaxBot : public TalkingRobot, public WalkingRobot
{
    public: explicit VaxBot(const string& Name):TalkingRobot(Name), WalkingRobot(Name) { this->Name = Name; }
    public: virtual ~VaxBot() = default;
    public: vector<string> GetCapabilities() { return { "Talking","Walking" }; }
};

They have a virtual function GetCapabilites().
Is there a way to rewrite GetCapabilites() in my VaxBot class to return all the inherited classes return values so that i dont have to explicitly write them like i did in here?


Solution

  • There isn't a simple one-line way in standard C++ to implement this sort of thing. For example, there is no way for a derived class to iterate over all its base classes, and call some member function in every base to collect the results, without explicitly naming all the bases/members separately.

    It is possible to call the inherited functions, and collect their results into a single vector. For example;

     std::vector<std::string> VaxBot::GetCapabilities()
     {
          std::vector<std::string> values(TalkingRobot::GetCapabilities());
    
          std::vector<std::string> more_values(WalkingRobot::GetCapabilities());
    
          values.insert(values.end(), more_values.begin(), more_values.end());
    
          return values;
     }
    

    The above can be extended if you have more than two such bases. That means explicitly replicating code but, as I said in my opening paragraph, there is no way to implement this sort of machinery implicitly.

    There are other problems with your code, but you haven't asked about those, so I won't address them. And, for readability, don't use the text public: on every line. Posting code that is unnecessarily unreadable is an effective way to reduce your chances of getting useful help, since it sets other people's teeth on edge.