I wish to have a pure virtual function, but I need to guarantee that all implementations of it include some bookkeeping.
Here is a workaround that achieves what I want, but it is clunky.
Is there a better approach? If not, is there a naming convention for a function like actually_do_it()?
class A
{
public:
virtual void do_it() final
{
bookkeeping();
actually_do_it();
}
protected:
virtual void actually_do_it() = 0;
private:
void bookkeeping() {}
};
class B : public A
{
void actually_do_it() {}
};
...
B b;
b.do_it();
CodePudding user response:
Is there a better approach? If not, is there a naming convention for a function like actually_do_it()?
"better" is purely subjective unless you define what "better" means. You approach is widely accepted and known as the Template Method Pattern (see eg https://en.wikipedia.org/wiki/Template_method_pattern).
I have seen it more commonly used when a method consists of several steps and the derived classes can customize the individual steps, but your use case is just as valid.