lundi 14 mars 2022

What is a pattern to ensure that every derived class (including derived classes of the immediate derived class) implement a method?

I have a base class and a number of generations of descendants (derived classes):

class Base{
    public:
    virtual void myFunc() = 0;
}
    
class Derived : public Base{
    //This class needs to implement myFunc()
}
    
class Derived2 : public Derived{
    //How to force this class to implement its version of myFunc(), and force it to call Derived::myFunc as well ?
}
    
class Derived3 : public Derived2{
    //.....should implement its own myFunc and call Derived2's mynFunc()...
}
    
class Derived4 : public Derived3{
    //.....should implement its own myFunc and call Derived3's mynFunc()...
}

Is there a pattern to ensure:

  • That each derived class (regardless of whether it is an immediate descendant of the base class, or a descendant of a descendant of the base class), implement its version of myFunc?
  • That each derived class calls its immediate parent class myFunc?

EDIT: The pattern that comes to mind to me is Decorator pattern, but wondering if there is some better way or variation.

Aucun commentaire:

Enregistrer un commentaire