Multiple Inheritance from two derived classes

706

Solution 1

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.

Solution 2

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)

Solution 3

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;
Share:
706
user3750455
Author by

user3750455

Updated on September 03, 2020

Comments

  • user3750455
    user3750455 over 3 years

    I'm new to lwjgl and openGL and i'm wanting to know how to do collision detection in 3D, I have a 3D sorta world setup but i don't know how to detect collisions.

    • datenwolf
      datenwolf over 9 years
      OpenGL just draws thing and there's no such concept as a scene or models in OpenGL. There are just points, lines and triangles. So for anything that goes beyond that you either have to program it yourself, or you make use of some 3rd party libraries. For your purpose I suggest you look for some physics simulation library; even if you don't want physics, collision detection is an integral part of the whole thing.