c++inheritanceclass-designnon-virtual-interface

nonvirtual interface idiom for more than two levels of inheritance?


The non-virtual interface idiom describes how the virtual methods are nonpublic customisation points, and public methods are nonvirtual to allow the base class to control at all times how the customisation points are called.

This is an elegant idiom and I like to use it, but how does it work if the derived class is a base class in itself


Solution

  • It works, because the derived class can override a private virtual function of a base class, even if the base class function overrides its base class function.

    This is perfectly legal:

    
    class Parent
    {
    public:
      int foo() {return bar();} // the non-virtual public interface
    private
      virtual int bar();
    };
    
    class Child : public Parent
    {
    private:
      virtual int bar();  // overrides Parent::bar()
    };
    
    class Grandchild : public Child
    {
    private:
      virtual int bar(); // overrides Child::bar();
    };