开发者

Sharing methods between two implementations of a virtual base class in C++

I have a virtual base class and two classes that implement th开发者_高级运维e various methods. The two classes have the same functionality for one of the methods. Is there away I can share the implementation between the two classes to eliminate redundant code? I tried making the first class a parent of the second class in addition to the virtual base class but got a bunch of errors.

EDIT - Thanks everyone for the replies. One thing I should have mentioned is that I cannot modify the virtual base class so just adding the code to the base class will not work.


Say, A is the base class, and B and C are classes that inherit from the base class. The method whose logic is shared between B and C is called SomeMethod. One of the following should do the trick, regardless of your use case:

  • Take the logic for B::SomeMethod and C::SomeMethod and copy-and-paste it into A::SomeMethod
  • Create a class D that provides the shared version of SomeMethod and have B and C derive from D, which will derive from A
  • Create a class SomeMethodImpl that just provides the implementation you want, and then the implementation of B::SomeMethod and C::SomeMethod will just delegate the method call to a private instance of SomeMethodImpl::SomeMethod


If you want to keep your base class as pure virtual, create another class that inherits from this one and implements that one function, and then have your two other classes inherit from this one:

class Base { public: virtual void TheFunction(); /* blah blah other virtual functions */ };
class OneFunctionImplemented : public Base { public: virtual void TheFunction() { DoSomething(); } };
class ChildClass1 : public OneFunctionImplemented { };
class ChildClass2 : public OneFunctionImplemented { };


Place the shared functionality in the base class. Both of the other classes will be able to access it from there.


I believe by virtual base class you mean a base class having a pure virtual function (an abstract class) and not deriving virtually from a base class. If this is the case, you can put the common implementation in this base class so that it is available for all the derived classes.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜