1

Is there an idiom I can use to help with implementing virtual functions that depend on the presence of a base class? For example, I have

class B {/* some abstract interface. */};

class A
{
public:
  virtual B* getB() {return nullptr;}
};

class C : public A, public B
{
public:
  B* getB() override {return this;}

  /* Implement B's interface here.*/
};

and I usually want to implement getB like this - could I somehow avoid having to repeat this for all leaf classes? I potentially have a few interface classes like B,

I know that one way to do it is to virtually inherit from A in both C and B, but I'd like to keep B unrelated from A, if at all possible.

4

1 回答 1

4

You can do it all in A:

class A
{
public:
    virtual B* getB() {return dynamic_cast<B*>(this);}
};

Note: virtual here is just to make class A polymorphic, a requirement of this use of dynamic_cast. We don't intend to override getB().

于 2013-03-30T15:23:23.813 回答