C++ Forcing Method Override In Concrete Class

后端 未结 5 2360

Is there a way in C++ to write a concrete class which when another class is derived from it, has a method which must be overriden. An abstract class allows the forcing of the de

5条回答
  •  花落未央
    2021-02-20 06:47

    Instead of defining intermediate classes, I find much more intuitive and clean leveraging on multiple inheritance. If our derived class inherits also from an abstract class which declares a pure virtual method with the same name as the one we want to force the override, then the compiler will not allow to instantiate objects of the derived type unless the method is actually overridden in the derived class.

    #include 
    
    struct Base{
      virtual void print() {std::cout << "Base" << std::endl; }  
    };
    
    struct RequireOverride {
      virtual void print() = 0;   
    };
    
    struct D1: Base, RequireOverride {
      virtual void print() {std::cout << "D1" << std::endl; }  
    };
    
    struct D2: Base, RequireOverride {
      // no override of function print() results in a compilation error
      // when trying to instantiate D2
    };
    
    
    int main() {
      D1 d1;
      d1.print(); //ok
    
    
      //D2 d2; // ERROR: cannot declare variable 'd2' to be of abstract type 'D2'
               // because the following virtual functions are pure within 'D2':
               // virtual void RequireOverride::print()
      return 0;
    }
    

    If you have multiple methods for which you want to enforce the existence of overrides, then you can put all of them in RequireOverride, or define more structures to multiple-inherit from, such as RequireOverrideMethod1, RequireOverrideMethod2, according to the context.

提交回复
热议问题