Search code examples
c++interfacevirtualaccess-specifier

What's the advantage of making methods public in an interface, but protected in the implementation?


In my C++ application I have an interface that looks like this:

class ICalculator
   {
   public:
      virtual double calculateValue(double d) = 0;
   };

I have implementations of this interface that look like this:

class MySpecificCalculator
   {
   public:
      virtual double calculateValue(double d);
   };

Now my colleague complains about this and tells me it's better to have the calculateValue method protected. That way, we can guarantee that the callers always pass via the interface and not via the direct implementation.

Is this a correct observation? Is it really better to make the implementation of an interface protected? Or can't we even make it private then?


Solution

  • Your colleague is right.

    Never make virtual functions public.

    Guideline #1: Prefer to make interfaces nonvirtual, using Template Method.

    Guideline #2: Prefer to make virtual functions private.

    Guideline #3: Only if derived classes need to invoke the base implementation of a virtual function, make the virtual function protected.

    For the special case of the destructor only:

    Guideline #4: A base class destructor should be either public and virtual, or protected and nonvirtual.