I have an existing class that declares a virtual method and defines a default implementation. Now I want to overload that method with a differend parameter and also give a default implementation. Additionaly I want to enforce the constraint, that if the first method got overridden by a subclass then the second (overloaded) virtual method must be overridden too.
Is this even possible inside C++? If so, is it possible at compile time?
Example code:
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 detect classes of type Derived
and enforce them to implement their verison of method(ParamB b)
.
No, you can't specify complex constraints on which sets of member functions must be overridden. The only constraints apply to individual functions; pure virtual (=0
) to mandate overriding, and (in C++11) final
to prevent overriding.
The best you can do is make both functions pure virtual, forcing the derived class to override both. This at least forces the author of the derived class to think about what needs overriding; it's impossible to override one and forget the other one.
You can still provide a default implementation, so that derived classes that don't want to override either function only need very short overrides that call the default versions.
I think C++ does not provide any means to detect such missing override in a child.
@larsmans: Making both methods pure virtuals leads to missing the default implementation.
@js_: could you elaborate a bit on your actual issue? What you are searching for seems to be conceptually not that clear to me.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With