Search code examples
c++publicprotected

Using protected or public with virtual function?


I always see a lot of examples where virtual functions are declared as protected in header files. Is it wrong to declare virtual functions as public? What is the best practice when using virtual functions?


Solution

  • Is it wrong to declare virtual functions as public?

    No.

    What is the best practice when using virtual functions?

    That completely depends on your use cases. The keywords per se are orthogonal in usage.

    Sometimes it's good to have protected virtual functions like with the template design pattern, most of the time the virtual functions are declared public to provide an interface.

    There are two design pattern categories the public and protected inheritance fall into:

    1. Template function pattern:

      class Base {
      public:
          void foo() {
              bar();
          };
      protected:
          virtual void bar() = 0;
      };
      
      class Implementation : public Base {
           void bar() {
               // provide the implementation
           }
      };
      
    2. Interface pattern:

      struct Interface {
          virtual void foo() = 0;
          virtual ~Interface() {}
      };
      
      class Implementation : public Interface {
      public:
           void foo() {
               // provide the implementation
           }
      };
      

    There are other design patterns, that may omit virtual at all (see CTRP), but the semantics of public and protected are still kept.