dimanche 10 avril 2022

How to enforce default behavior in a virtual function

For example, say I have a basic data object class as below.

class DataObject {
   protected:
      bool data_changed;
      virtual void save() {}
      virtual void load() {}
   public:
      virtual void idle() { 
          if (data_changed) {
              save();
              data_changed = false;
          }
      }
};

The idea is that "idle" is called periodically from some main looping thread and performs non-critical updates.

Now I want derived classes to be able to have their own idle functions. But I don't want to lose the default behavior.

One solution is to say "remember to call DataObject::idle() from overridden idle() functions".

Like this:

class ChildData : public DataObject {
   public:
      virtual void idle() override {
          //do something
          
          DataObject::idle(); //remember to call parent idle!
      }
};

But this is very dangerous as people can just forget.

Is there a way to enforce this somehow? Or make it automatic, like a virtual destructor?

(My current "workaround" is to have 2 functions, one the parent_idle that does the important stuff, and then one overridable child_idle that derived functions can override. But this is a bit messy, and also you have to make a whole new set of functions again if you want some child function to enforce its own default...)

Aucun commentaire:

Enregistrer un commentaire