Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any difference between a private and protected pure virtual function?

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.

like image 426
Prismatic Avatar asked Mar 19 '12 01:03

Prismatic


2 Answers

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; } }; 
like image 147
LiquidAsh Avatar answered Sep 20 '22 14:09

LiquidAsh


First pure virtual function can be implemented!

#include <iostream>

class Animal
{
public:
  void eat(void);
protected:
  virtual void doEat(void)=0;
};
void Animal::eat(void)
{
  doEat();
}
void Animal::doEat(void)
{
  std::cout << "animal" << std::endl;
}

class Tiger : public Animal
{
private:
  virtual void doEat(void)
  {
    Animal::doEat();//here is the difference between protected and private
    std::cout << "tiger" << std::endl;
  }
};

int main(void)
{
  Animal *p = new Tiger();
  p->eat();
  return 0;
}

Second,Herb Sutter explained when to use "virtual private" or "virtual protected",you can read from this article.I think this explains why we do this not only we can!The article says:"Prefer to make virtual functions private,Only if derived classes need to invoke the base implementation of a virtual function, make the virtual function protected",your question is about pure virtual function,I am not quite sure whether satisfy this principle.

like image 27
gwshi Avatar answered Sep 19 '22 14:09

gwshi