1

Let's imagine I have the following code:

class Base {
  virtual void myFunc();
};

class Subclass1 : public Base { // OK
  virtual void myFunc() override; // overrides the base function
};

class Subclass2 : public Base { // How to make this fail ?
  // does not declare an override for myFunc
};

Is there any way in C++ to make compilation fail because Subclass2 does not implement its variant of myFunc() ? I know how to make the opposite, that is to make compilation fail because Subclass1 overrides myFunc() (by using final), but I'm not aware of any mechanic to achieve what I want in C++11.

I'm curious about possibilities in later C++ standards as well.

Vincent Fourmond
  • 3,038
  • 1
  • 22
  • 24
  • 5
    Make the function in `Base` pure virtual: `virtual void myFunc() = 0;` – Igor Tandetnik Sep 06 '20 at 21:47
  • 1
    There's nothing in C++ that will require a subclass to always override a method in the superclass. The only requirement is that a pure virtual function must be overridden either by the class being constructed, or one of the intermediate subclasses. That's the only way that C++ works. – Sam Varshavchik Sep 06 '20 at 21:48
  • Does this answer your question? [how to implement Interfaces in C++?](https://stackoverflow.com/questions/9756893/how-to-implement-interfaces-in-c) – Den-Jason Sep 06 '20 at 22:14

1 Answers1

4

You can force one subclass level to override a method, by making it 'pure' (virtual method()=0;), but you cannot force multiple levels to each override it again - and that should really not be your concern.

In other words, if you provide a base (or derived) class to an enduser, you can force him to override (define) a method in his derived class. If that user wants to derive from his derived class again, it’s his business to decide if the next (further) derived class needs a different override or not.

user207421
  • 305,947
  • 44
  • 307
  • 483
Aganju
  • 6,295
  • 1
  • 12
  • 23