Is it possible to define / state that if one virtual function becomes overridden, the other one is also redefined?

I have an existing class that declares a virtual method and defines a default implementation. Now I want to overload this method with the differend parameter, and also provide a default implementation. In addition, I want to apply a restriction so that if the first method receives an overridden subclass , then the second (overloaded) virtual method must be overridden .

Is this possible inside C ++? If so, is this possible at compile time?

Code example:

class ParamA {}; class ParamB {}; class Base { public: virtual void method(ParamA a) { // default behavior } virtual void method(ParamB b) { // default behavior } } class Derived : public Base { public: virutal void method(ParamA) { // special behavior } } 

My goal is to discover classes like Derived and enforce them in order to implement their method(ParamB b) .

+6
source share
4 answers

No, you cannot specify complex constraints over which many member functions must be redefined. The only restrictions apply to individual functions; pure virtual ( =0 ) to override the mandate and (in C ++ 11) final to prevent overriding.

The best thing you can do is make both functions pure virtual, forcing the derived class to override both. This, at least, makes the author of the derived class think about what needs to be redefined; it is impossible to redefine one and forget the other.

You can still provide a default implementation, so derived classes that do not want to override any function need only very short overrides that invoke the default versions.

+5
source

I think C ++ does not provide any means to detect such a missing override in a child element.

@larsmans: creating both pure virtual methods results in no default implementation.

@js_: could you talk a little bit about your real problem? What you are looking for is apparently conceptually not so clear to me.

+1
source

How to create a parent class from which Base is inherited? These 2 functions will be purely virtual in the Parent class. The resulting classes inherit from Parent (not Base ) and will have to perform both functions.

0
source

If you all need to work with the parent class, then no. This is not possible either at compile time or as a run-time check.

Of course, you can enter some macros (for example, OVERRIDE_METHODS ... I'm sure you understand what I'm talking about), but nothing can stop users from ignoring them and overriding only one of the specified methods.

Plus, these macros will make the code pretty ugly.

0
source

Source: https://habr.com/ru/post/905909/


All Articles