Using Sister's Inheritance

suppose that some (outdated) code that cannot be touched is declared

struct B{ public: void f(){} }; 

and suppose that

 struct A{ public: virtual void f()=0; }; 

you can make a subclass call AB :: f without explicitly calling f (), i.e. instead of

  struct C: public A, public B{ void f(){ B::f(); } }; 

having something like

  struct C:virtual public A,virtual public B{ }; 

(note that this last class is abstract, since the A :: f compiler is undefined)

+7
source share
5 answers

Directly in C ++, it is impossible to send polymorphically based on some implicit mapping of functions B to A. You can resort to code generation using gccxml or other similar products, but if there are only a hundred functions, a macro can in any case reduce redirection to single-line - not Itโ€™s worth introducing additional tools if you donโ€™t have thousands and thousands to do it.

+1
source

Make an implementation of A that delegates to B :

 class A_Impl : public A { public: virtual void f() { bf(); } private: B b; } 

Deploy C by deriving from A_Impl :

 class C: public A_Impl { }; 

Or, if you want to show A in the inheritance hierarchy, publicly publish from A and privately from A_Impl :

 class C: public A, private virtual A_Impl { }; 
+1
source

You can do something like:

 void C::f() { B* b = this; b->f(); } 
0
source

No, you cannot do this. And from the fragment you showed us, it seems that B should be a member of C by composition, not inheritance. You just need to write some forwarding functions (or a script to automatically create them).

0
source

So, you have 100 pure virtual functions in A, the implementation of these functions in B, and you want to avoid writing a reimplementation of all these functions in C to call B. There is no way to force the compiler to use the implementation of B automatically. Instead of fighting the compiler (you'll lose every time!), Rethink the inheritance graph . It is possible to make B a subclass of A, and then deduce C from B. Or use 100 methods from B to a specific subclass of A.

Programming is the art of solving problems within the limits provided by your tools. When you find yourself in difficulty with your tools, you need to either reconsider your approach to the problem, or use different tools.

-one
source

All Articles