Using C++, how do I correctly inherit from the same base class twice?

前端 未结 8 1066
醉酒成梦
醉酒成梦 2020-12-29 10:35

This is our ideal inheritance hierarchy:

class Foobar;

class FoobarClient : Foobar;

class FoobarServer : Foobar;

class WindowsFoobar : Foobar;

class UnixF         


        
相关标签:
8条回答
  • 2020-12-29 11:20

    There is nothing "illegal" about having the same base class twice. The final child class will just (literally) have multiple copies of the base class as part of it (including each variable in the base class, etc). It may result in some ambiguous calls to that base classes' functions, though, which you might have to resolve manually. This doesn't sound like what you want.

    Consider composition instead of inheritance.

    Also, virtual inheritance is a way to fold together the same base class which appears twice. If it really is just about data sharing, though, composition might make more sense.

    0 讨论(0)
  • 2020-12-29 11:22

    You're in C++, you should get friendly with templates. Using the template-argument-is-a-base-class pattern, you'll not need any multiple inheritance or redundant implementations. It will look like this:

    class Foobar {};
    
    template <typename Base> class UnixFoobarAspect : public Base {};
    template <typename Base> class WindowsFoobarAspect : public Base {};
    template <typename Base> class FoobarClientAspect : public Base {};
    template <typename Base> class FoobarServerAspect : public Base {};
    
    typedef UnixFoobarAspect<FoobarClientAspect<Foobar>/*this whitespace not needed in C++0x*/> UnixFoobarClient;
    typedef WindowsFoobarAspect<FoobarClientAspect<Foobar> > WindowsFoobarClient;
    typedef UnixFoobarAspect<FoobarServerAspect<Foobar> > UnixFoobarServer;
    typedef WindowsFoobarAspect<FoobarServerAspect<Foobar> > WindowsFoobarServer;
    

    You might also consider using the curiously recurring template pattern instead of declaring abstract functions to avoid virtual function calls when the base class needs to call a function implemented in one of the specialized variants.

    0 讨论(0)
提交回复
热议问题