Multiple Inheritance from two derived classes

旧街凉风 提交于 2019-11-27 04:46:06

It looks like you want to do virtual inheritance. Whether that turns out to actually be a good idea is another question, but here's how you do it:


class AbsBase {...};
class AbsInit: public virtual AbsBase {...};
class AbsWork: public virtual AbsBase {...};
class NotAbsTotal: public AbsInit, public AbsWork {...};

Basically, the default, non-virtual multiple inheritance will include a copy of each base class in the derived class, and includes all their methods. This is why you have two copies of AbsBase -- and the reason your method use is ambiguous is both sets of methods are loaded, so C++ has no way to know which copy to access!

Virtual inheritance condenses all references to a virtual base class into one datastructure. This should make the methods from the base class unambiguous again. However, note: if there is additional data in the two intermediate classes, there may be some small additional runtime overhead, to enable the code to find the shared virtual base class.

You need to to declare the inheritance as virtual:

struct AbsBase {
          virtual void init() = 0;
          virtual void work() = 0;
};

struct AbsInit : virtual public AbsBase {
          void init() {  }
};

struct AbsWork : virtual public AbsBase {
          void work() { }
};

struct NotAbsTotal : virtual public AbsInit, virtual public AbsWork {
};

void f(NotAbsTotal *p)
{
        p->init();
}

NotAbsTotal x;

It can be done, although it gives most the shivers.

You need to use "virtual inheritance", the syntax for which is something like

class AbsInit: public virtual AbsBase {...};
class AbsWork: public virtual AbsBase {...};
class NotAbsTotal: public AbsInit, public AbsWork {...};

Then you have to specify which function you want to use:

NotAbsTotal::work()
{
    AbsInit::work_impl();
}

(UPDATED with correct syntax)

You have to start thinking in the terms of what you are trying to model here.

Public inheritance should only ever be used to model an "isa" relationship, e.g. a dog is a animal, a square is a shape, etc.

Have a look at Scott Meyer's book Effective C++ for an excellent essay on what the various aspects of OO design should only ever be interpreted as.

Edit: I forgot to say that while the answers so far provided are technically correct I don't think any of them address the issues of what you are trying to model and that is the crux of your problem!

HTH

cheers,

Rob

I found a good and simple example at the below link. The article explains with an example program for calculating the area and perimeter of a rectangle. You can check it..cheers

Multilevel Inheritance is an inheritance hierarchy wherein one derived class inherits from multiple Base Classes. Read more..

http://www.mobihackman.in/2013/09/multiple-inheritance-example.html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!