'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...)
Solution 1:[1]
Maybe you could write it:
...
void idle_start() { // not virtual, main looping thread calls this
idle();
if (data_changed) {
save();
data_changed = false;
}
}
virtual void idle() { } // virtual, noop by default
...
That depends if you want to have your derived behavior before the mandatory base behavior.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
