Forcing a derived class to overload a virtual method in a non-abstract base class

此生再无相见时 提交于 2019-12-23 05:08:56

问题


I'm writing some code using a simple clone pattern, I'd like it if I were able to force derived classes to override that clone pattern, but retain the ability to use my base class. (So I don't want to declare the clone method to be pure virtual.)

Is there anyway to enforce this restriction at the compiler level?


回答1:


Unfortunately there is just no way to make this happen in C++. You can't force a non-abstract method to be overridden in child classes. However, I might note that concrete base classes should be fairly rare in C++ and you might want to reconsider your design. With more information about your overall aims we might be able to provide a better answer for your precise needs.




回答2:


It has been some time I touched C++, but I do remember you can have pure virtual method with body.

// in header
class YourBase {
public:
  virtual Foo bar() = 0;
};

// in source
Foo YourBase::bar() {
  // a default impl
}

That should force the child class to override bar(), while leaving a usable impl of bar() in YourBase




回答3:


Unfortunately you can't enforce at compile time that a class overrides a method of a concrete base class, but you can simply assert in each clone function implementation that the type is the type of the class where that implementation resides,

assert( typeid( *this ) == typeid( ThisClass ) );

and then run a test that exercises the cloning functionality of every class.



来源:https://stackoverflow.com/questions/12632747/forcing-a-derived-class-to-overload-a-virtual-method-in-a-non-abstract-base-clas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!