Skip to main content
edited tags
Link
Christophe
  • 80.6k
  • 11
  • 132
  • 199
Source Link

Using virtual inheritance for an interface system based on abstract classes

I want to use a physics engine (like bullet or PhysX) in my program, however I want to hide the actual physics engine from it, so I can easily swap it out with another during run-time (e.g. switch between bullet and PhysX without requiring any changes to my main program).

To do so, I have created some abstract classes, which will be used by the program directly:

class IShape
{
public:
    virtual ~IShape()=default;
};

class IConvexShape
    : virtual public IShape
{
public:
};

class IConvexHullShape
    : virtual public IConvexShape
{
public:
};

Then I can just implement these classes for a specific physics engine like bullet:

class BtShape
    : virtual public IShape
{
public:
};

class BtConvexShape
    : virtual public IConvexShape,
    public BtShape
{
public:
};

class BtConvexHullShape
    : virtual public IConvexHullShape,
    public BtConvexShape
{
public:
};

The problem is that IShape implements some base functionality that should be used for all other shape types, and BtShape implements some base functionality that should be used for all other bullet shape types, which means I have to use virtual inheritance (Same goes for IConvexShape / BtConvexShape.):

UML depiction of the class interface.

While this works, I'm a bit hesitant to go further with this, since it's usually recommended to avoid virtual inheritance altogether.

Can I expect any problems with this approach? Are there any alternative methods I can use instead?