Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using sister inheritance

let us suppose some (legacy) code, which cannot be touched, declare

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

and let us suppose to have

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

is it possible to make an A subclass call B::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, for the compiler A::f is not defined)

like image 843
Fabio Dalla Libera Avatar asked Apr 10 '12 05:04

Fabio Dalla Libera


2 Answers

Directly in C++, it is impossible to dispatch polymorphically based on some implicit matching of B's functions to A's. You could resort to some kind of code generation using gccxml or other similar products, but if there's only a hundred functions a macro can reduce the forwarding to a one-liner anyway - not worth introducing extra tools unless you've got thousands and thousands of these to do.

like image 132
Tony Delroy Avatar answered Nov 14 '22 23:11

Tony Delroy


Make an implementation of A which delegates to B:

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

Implement C by deriving from A_Impl:

class C: public A_Impl
{
};

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

class C: public A, private virtual A_Impl
{
};
like image 26
Peter Wood Avatar answered Nov 15 '22 01:11

Peter Wood