C++ – ny difference between a private and protected pure virtual function

cinheritancepure-virtual

I can understand that there might be a reason to declare an implemented (as opposed to pure) virtual function private or protected. Afaik, if you declare an implemented virtual method as protected, your child class can call the base class's method (and nobody else can). If you declare it private, than only the base class can call the default implementation of the virtual method.

However, with pure virtuals, there is no base implementation… So isn't it functionally equivalent to declare a pure virtual as either private or protected? A protected pure virtual doesn't make sense because you can't ever invoke the base class's corresponding method. Are there any scenarios where a protected pure virtual makes any sense?

There are a few similar topics on SO, but I couldn't find anything that concisely answered my question.

Best Answer

Are there any scenarios where a protected pure virtual makes any sense?

I think that you mean private here (instead of protected), but think I understand your point. In fact, the access type of a pure virtual can be overridden in derived classes. Here's an example that might help you see the difference between a private and protected pure virtual:

class Parent
{
  protected: virtual void foo() = 0;
  private:   virtual void bar() = 0;
  public:            void test() { foo(); bar(); }
};

class Child : public Parent
{
  public: void test2() { foo(); /* bar(); // cannot be called here */ }
};

class GrandChild : public Child
{
  // access types here can be anything for this example
  public: void foo() { cout << "foo" << endl; }
  public: void bar() { cout << "bar" << endl; }
};