Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Add functionality to a pure virtual function in C++?

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()?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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();

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading