Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to determine/assert, that if one virtual function gets overridden, another one is overridden too?

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).

like image 743
js_ Avatar asked Jan 13 '12 13:01

js_


2 Answers

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.

like image 127
Mike Seymour Avatar answered Oct 22 '22 19:10

Mike Seymour


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.

like image 25
boto Avatar answered Oct 22 '22 20:10

boto