0

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?

OmnipotentEntity
  • 16,531
  • 6
  • 62
  • 96
  • Even if your base class `clone` method was pure virtual that wouldn't force the child of a child to implement it. You could achieve this if you required derived classes to include a macro of some sort in their declaration (that declared the overridden method so they have to implement it), but that's not ideal. – paddy Sep 28 '12 at 02:34
  • 1
    `virtual` implies dynamic polymorphism, which is inherantly a runtime operation, and invariants must be enforced with runtime checks. If you want compile-time operations and invariant checks, use [CRTP](http://en.wikipedia.org/wiki/Curiously_recurring_template_pattern) for static polymorphism instead, and something like this becomes completely trivial. – ildjarn Sep 28 '12 at 03:08

3 Answers3

4

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.

Mark B
  • 95,107
  • 10
  • 109
  • 188
1

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

Adrian Shum
  • 38,812
  • 10
  • 83
  • 131
  • the implementation doesn't help, since it's no use in using a cloning implementation that's cloning only the abstract class part. the only effect is that `YourBase` cannot be separately instantiated, since it's abstract. – Cheers and hth. - Alf Sep 28 '12 at 03:01
  • maybe your "ability to use my base class" is a bit too vague. I thought you mean ability to use the impl in base class in derived class. – Adrian Shum Sep 28 '12 at 03:50
1

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.

Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331