简体   繁体   中英

C++ - Multiple Inheritance

I have a requirement which will form the diamond dread pattern. But I have come across comments from stack overflow mates that if the virtual base class is a pure abstract class, then the diamond pattern is not so much of a concern. Can someone please expand on this as to why it is so?

Multiple inheritance in C++ is a powerful, but tricky tool, that often leads to problems if not used carefully.

Following article will teach you how to use virtual inheritance to solve some of these common problems programmers run into.

Solving the Diamond Problem with Virtual Inheritance

try to implement dimond as follow:Article gives very good explanation

class storable 
{
        public:
        storable(const char*);
        virtual void read()=0; //this becomes pure virtual making storable an abstract
        virtual void write(); //class
        virtual ~storable();
        private:
        ....
}

class transmitter: public virtual storable 
{
        public:
        void write()
        {
                read();
                ....
        }
} 

class receiver: public virtual storable
{
        public:
        void read();
}

class radio: public transmitter, public receiver
{
        public:
        ...
}

int main()
{
        radio *rad = new radio();
        receiver *r1 = rad;
        transmitter *r2 =rad;

        rad->write();
        r1->write();
        r2->write();
        return 1;
}

I am not sure of how much you know or don't know about virtual inheritance or the diamond pattern. The simple answer is that if inheritance is not virtual (from the root of the diamond) then instead of a diamond you have a V , where the complete type contains two independent copies of the base class. Virtual inheritance is basically telling the compiler that you only want one copy of the base in the complete type (most derived), regardless of how many intermediate types mention that base as virtual in their inheritance relationship.

Of course, the approach brings up its own problems as for example the fact that encapsulation is somehow broken (the derived type must know of the inheritance relationship of is bases with respect to their virtual base in order to call the constructors), and the operations on the virtual base subobject will be somehow more complex and expensive.

Have a look at this link - How can I avoid the Diamond of Death when using multiple inheritance?

I believe the comments will give you some insight into this

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM