Search code examples
c++overridingmultiple-inheritance

How do I choose the base class when overriding a function in c++?


I have two base classes and a class that inherits both base classes. Both base classes have a virtual function with the same signature, and I want to provide different implementations in the derived class to each virtual function.

class A{
    virtual void f() = 0;
}
class B{
    virtual void f() = 0;
}
class Derived:public A, public B{
    void A::f() override{ // Error
        ...
    }
    void B::f() override{ // Error
        ...
    }
}

What is the correct way to do this? (I cannot rename the virtual function. Actually the two base classes are generated from the same template class.)


Solution

  • template <typename T>
    class AShim : public A {
      void f() override {
        static_cast<T*>(this)->A_f();
      }
    };
    
    template <typename T>
    class BShim : public B {
      void f() override {
        static_cast<T*>(this)->B_f();
      }
    };
    
    class Derived: public AShim<Derived>, public BShim<Derived> {
      void A_f();
      void B_f();
    };