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

前端 未结 8 1102
醉酒成梦
醉酒成梦 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:15

    It would work, although you'd get two copies of the base Foobar class. To get a single copy, you'd need to use virtual inheritance. Read on multiple inheritance here.

    class Foobar;
    
    class FoobarClient : virtual public Foobar;
    
    class FoobarServer : virtual public Foobar;
    
    class WindowsFoobar : virtual public Foobar;
    
    class UnixFoobar : virtual public Foobar;
    

    However, there are many problems associated with multiple inheritance. If you really want to have the model presented, why not make FoobarClient and FoobarServer take a reference to Foobar at construction time, and then have Foobar& FoobarClient/Server::getFoobar ?

    Composition is often a way out of multiple inheritance. Take a example now:

    class WindowsFoobarClient : public WindowsFoobar 
    {
        FoobarClient client;
    public:
        WindowsFoobarClient() : client( this ) {}
        FoobarClient& getClient() { return client }
    }
    

    However care must be taken in using this in the constructor.

提交回复
热议问题