Search code examples
c++inheritancemultiple-inheritance

How to call superclass method in multiple-inheritance?


I have a class C that inherits both from Ai and B. A and B are unrelated. This is all best explained with the code below. In main(), I have a variable a defined as std::unique_ptr<A>, but initialized with C. I cannot change this definition.

My question is, given a defined like this, how can I call functions defined in B or C or Ai correctly?

#include <memory>

class A 
{ 
public: 
  void fun_a() {}
}; 
  
class B 
{ 
public: 
  void fun_b() {}
}; 

class Ai : public A
{ 
public:
    void fun_ai() {}
}; 
  
class C: public Ai, public B
{ 
public:
    void fun_c() {}
}; 
  
int main() 
{ 
    // I cannot change the following definition:
    std::unique_ptr<A> a = std::make_unique<C>();
    
    a->fun_a();
    //a->fun_b(); // How ?
    //a->fun_c(); // How ?
    //a->fun_ai(); // How ?
    
    return 0; 
}

Solution

  • You can static_cast to C*:

    static_cast<C*>(a.get())->fun_b();
    static_cast<C*>(a.get())->fun_c();
    static_cast<C*>(a.get())->fun_ai();
    

    or you could make it polymorphic:

    class A { 
    public: 
        virtual ~A() = default;
        void fun_a() { std::cout << "fun_a\n"; }
    };
    

    and then dynamic_cast:

    dynamic_cast<B*>(a.get())->fun_b();
    dynamic_cast<C*>(a.get())->fun_c();
    dynamic_cast<Ai*>(a.get())->fun_ai();
    

    Note: dynamic_casts to pointer types may fail and return nullptr so, if there's any doubt, check the return value.

    Demo