How can a C++ base class determine at runtime if a method has been overridden?

后端 未结 3 1325
感动是毒
感动是毒 2021-01-13 11:55

The sample method below is intended to detect whether or not it has been overridden in a derived class. The error I get from MSVC implies that it is simply wrong to try to g

3条回答
  •  醉酒成梦
    2021-01-13 12:28

    There is no way to determine if a method has been overridden, except for pure virtual methods: they must be overridden and non-pure in a derived class. (Otherwise you can't instantiate an object, as the type is still "abstract".)

    struct A {
      virtual ~A() {} // abstract bases should have a virtual dtor
      virtual void f() = 0; // must be overridden
    }
    

    You can still provide a definition of the pure virtual method, if derived classes may or must call it:

    void A::f() {}
    

    Per your comment, "If the method had not been overridden it would mean it is safe to try mapping the call to the other method instead."

    struct Base {
      void method() {
        do_method();
      }
    
    private:
      virtual void do_method() {
        call_legacy_method_instead();
      }
    };
    
    struct Legacy : Base {
    };
    
    struct NonLegacy : Base {
    private:
      virtual void do_method() {
        my_own_thing();
      }
    };
    

    Now, any derived class may provide their own behavior, or the legacy will be used as a fallback if they don't. The do_method virtual is private because derived classes must not call it. (NonLegacy may make it protected or public as appropriate, but defaulting to the same accessibility as its base class is a good idea.)

提交回复
热议问题