oLen oLen - 3 days ago 6
C++ Question

Can one hide parts of the inheritance hierarchy in C++?

Consider the following:

Class

B
inherits publicly from class
A
. Both are provided in a library and I cannot modify them.

I want to implement a class
Foo
that derives from
B
, but I want to allow users of
Foo
to use only public functions of
A
and
Foo
(not from
B
). For them, it is not relevant that
Foo
inherits from
B
, this is in principle an implementation detail that I cannot avoid.

So, in principle I want
Foo
to inherit publicly from
A
, but privately from
B
.

Is there some construct in C++ that would allow me to do this?

I must add that virtual inheritance is not an option since
A
, in my case, derives from
QObject
(see Is it safe to use *virtual* multiple inheritance if QObject is being derived from DIRECTLY?).

(NB: For interested people: in my case,
A
is
QWindow
and
B
is
Qt3DExtras::Qt3DWindow
)

Answer

The closest you can do in c++ is this:

class Foo : private B {
  public:
    using A::foo; // Expose function foo in Foo's API.
    using A::bar;
    operator A&() { return *this; } // Implicit conversion to `A` when needed.
    operator A const&() const { return *this; }
};
Comments