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)
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; }
};
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
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With