Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 358
oLen Avatar asked Nov 29 '16 08:11

oLen


2 Answers

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; }
};
like image 53
StoryTeller - Unslander Monica Avatar answered Nov 06 '22 03:11

StoryTeller - Unslander Monica


Since this is Qt, I think this is the closest you can do:

struct Foo : A {
    // override all function of A, forward its to B
private:
    B b; // or pointer to B, it's depend on your design
};
like image 34
Danh Avatar answered Nov 06 '22 04:11

Danh