Search code examples
c++inheritancemultiple-inheritance

Is it possible to make a class a child of two distinct hierarchies?


I would like to do the following:

class MyA : public ExternalA {
// some code
}

class MyB : public ExternalB {
// the same code as above
}

i.e. I want to extend both ExternalA and ExternalB the same way. But (for reasons) I do not want to do:

class MyC : public ExternalA, public ExternalB
{
// same code
}

PS, Edit: My question is about how I could avoid duplicating the code sections in the definitions of MyA and MyB.


Solution

  • template might help:

    template <typename Base>
    class MyDerived : public Base
    {
        // some code
    };
    
    using MyA = MyDerived<ExternalA>;
    using MyB = MyDerived<ExternalB>;