0

I have seen a pattern in code where you hide some of your virtual functions behind non virtual functions like this:

class IApa {
   public:
   virtual ~IApa() = default;

   void update() {
      doUpdate();
   };

   private:
   virtual void doUpdate() = 0;
};

class Apa: public IApa {
   private:

   void doUpdate() override {...}
};

I know that it is some kind of code pattern, but to me it only looks like you pollute the interface. What is the reason for using a pattern like this?

It is also possible that the examples I have seen is implemented wrong, do you know any design pattern that is similar to this, and what is the motivation for doing it?

Lasersköld
  • 2,028
  • 14
  • 20
  • 1
    [Non Virtual Interface](https://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Non-Virtual_Interface) idiom. C++ can use a private virtual. C# does not allow for private virtual (for some inexplicable reason; it's a useful access). The public facing function should *not* be virtual, because it is used to enforce pre- and post-conditions (if any). The idiom is not very useful for small projects; very helpful for large projects. – Eljay Jul 01 '21 at 12:46
  • 1
    The reason is that `update` might, later, need to be changed to do something in addition to calling `do_update()`. This approach provides no-cost flexibility for future maintenance. It's done throughout the C++ standard library. – Pete Becker Jul 01 '21 at 12:47
  • Original motivation: A `public virtual` function in an interface is declaring two things. "This is part of this class's public API" and "this is a customization point where child classes are expected to provide functionality". There's no fundamental reason to join these two declarations at the hip, and the NVI idiom is a way of making them independent. – Nathan Pierson Jul 01 '21 at 13:56
  • @NathanPierson Yes, its just that, as with pimpl, it comes at the cost of duplicating all virtual function declarations. For a codebase as the one I work in where the company can change all the code, If you wanted to have preconditions added, you could just convert the virtual function to a non virtual one (that does the preconditioning and calls the do_\*-function) and then recompile the codebase. If you apply all these idioms without thinking the codebase will instantly be twice the size without reason :/ – Lasersköld Jul 05 '21 at 07:43
  • It doesn't come close to doubling the size of the codebase. Each virtual function will correspond to one additional declaration and definition _in the abstract base class_, but you won't have any new functions in any of the concrete classes. Or are you saying that the codebase doubles in size without reason if you apply this idiom _and also_ a bunch of additional, unspecified, unjustified idioms? – Nathan Pierson Jul 05 '21 at 15:47
  • @NathanPierson Yes – Lasersköld Jul 06 '21 at 07:25

0 Answers0