Ichthyo
Ichthyo

Reputation: 8359

Cost of virtual inheritance from an interface

This is an attempt to understand the impact of using virtual base class inheritance, especially regarding runtime cost. The situation I have in mind also involves Interfaces (or ABC s for that).

   I----------
 / | \        |
D1 D2 D3      Isub
      |     /
      D3Dec

So, we have an Interface I and we have different implementations D1, D2, and D3. But now the twist is, there is a special decorator, which wraps just some (arbitrary) I implementation and then adds an extended feature based on the contract expressed through I.

Thus, from a logical or design viewangle, it would be desirable to express that extended ability through a sub-interface Isub derived from I. Thus any Isub automatically also fulfils the I contract.

Question: Performance impact

Now, to implement such in C++, any implementation of interface I must be done virtual, and likewise, Isub must inherit virtual from I, otherwise we'd end up with two I subobjects residing in D3Dec.

The obvious alternative is of course to cut the link between I and Isub, turning it into a trivial mix-in. This works, but is ugly, since Isub does not make much sense on its own, independent of I. Both even use the same data types on the signatures, etc...

Upvotes: 2

Views: 376

Answers (1)

Mark Ransom
Mark Ransom

Reputation: 308206

You can avoid the diamond inheritance problem entirely by making the interface class a template parameter of the concrete class. Then there's no more need for virtual class inheritance.

class I { ... };

template<class Ifc>
class D3Impl : public Ifc
{ ... };

typedef D3Impl<I> D3;

class Isub : public I { ... };

class D3Dec : public D3Impl<Isub>
{ ... };

Upvotes: 2

Related Questions