OmnipotentEntity
OmnipotentEntity

Reputation: 17131

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

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?

Upvotes: 0

Views: 1658

Answers (3)

Cheers and hth. - Alf
Cheers and hth. - Alf

Reputation: 145409

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.

Upvotes: 1

Adrian Shum
Adrian Shum

Reputation: 40056

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

Upvotes: 1

Mark B
Mark B

Reputation: 96291

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.

Upvotes: 4

Related Questions