Search code examples
c++inheritancemultiple-inheritance

Multiple Inheritance in C++, choose from which class take the member


Consider the following code:

class A {
  public:
  virtual void f() {
    std::cout << "A-F" << std::endl;
  }

  virtual void g() {
    std::cout << "A-G" << std::endl;
  }
};

class B: public A {
  public:
  void f() {
    std::cout << "B-F" << std::endl;
  }
};

class C: public A {
  public:
  void g() {
    std::cout << "C-G" << std::endl;
  }
};

Now I want to define a class C whose member f is class B, and member g is from class A. Something like this:

class D: public B, public C {
  public:
  \\ Inheritate f from B

  \\ Inheritate g from C
};

How do I do it in c++?


Solution

  • You can achieve the same if your C only inherits from B, i.e. class C: public B {/*...*/}. If you really want your C to inherit from both, B and A, you have to use virtual inheritance (see the virtual keywords when inheriging from A):

    #include <iostream>
    
    class A {
      public:
      virtual void f() {
        std::cout << "A-F" << std::endl;
      }
    
      void g() {
        std::cout << "A-G" << std::endl;
      }
    };
    
    class B: virtual public A {
      public:
      void f() override {
        std::cout << "B-F" << std::endl;
      }
    };
    
    class C: virtual public A, public B {
      public:
    };
    
    
    int main() {
    
        C c;
        c.f();
        c.g();
    
        return 0;
    }
    

    This prints

    B-F
    A-G
    

    Unreladed: I'd recommend to use the override (or final) keyword, especially when dealing with more complex class hierarchies.

    EDIT

    As OP changed the question:

    #include <iostream>
    
    class A {
      public:
      virtual void f() {
        std::cout << "A-F" << std::endl;
      }
    
      virtual void g() {
        std::cout << "A-G" << std::endl;
      }
    };
    
    class B: virtual public A {
      public:
      void f() override {
        std::cout << "B-F" << std::endl;
      }
    };
    
    class C: virtual public A {
      public:
      void g() override {
        std::cout << "C-G" << std::endl;
      }
    };
    
    class D: public B, public C {
      public:
      // Inherits f from B
      // Inherits g from C
    };
    
    
    int main() {
    
        D d;
        d.f();
        d.g();
    
        return 0;
    }
    

    This prints:

    B-F
    C-G
    

    as required.

    Note That I am not a big fan of virtual inheritance and maybe there is a better solution for your problem. However, this depends on your exact problem.