C++: Private virtual functions vs. pure virtual fu

2019-03-27 20:39发布

问题:

Possible Duplicate:
Private virtual method in C++

If I understood correctly from this post (Private virtual method in C++), making a virtual function in a base class makes the derived classes able to override it. But it seems things stop there.

But if the base class virtual function is pure, that forces the derived classes to implement the function. Hence, a pure (public) virtual function is merely an interface. I can see a benefit here.

On the other hand, by making a base class virtual function private, only gives the derived class the ability to override the function, but I see no benefit of this. It's as if that private virtual function is not even there. The derived class obviously does not know about the existence of that virtual function in base class because its private, so is there any benefit of declaring a base class private function virtual, in term of inheritance or polymorphism?

Also, is there any situation where a base class would declare a function 'pure virtual' and 'private'?

Thank you.

回答1:

One benefit is in implementing the template method pattern:

class Base {

 public :
  void doSomething() {
    doSomething1();
    doSomething2();
    doSomething3();
  }
 private:
   virtual void doSomething1()=0;
   virtual void doSomething2()=0;
   virtual void doSomething3()=0;
};


class Derived : public Base {
  private:
   virtual void doSomething1() { ... }
   virtual void doSomething2() { .... }
   virtual void doSomething3() { .... }
}

This allows the derived classes to implement each piece of a certain logic, while the base class determines how to put these pieces together. And since the pieces don't make sense by themselves, they are declared private and so hidden from client code.



回答2:

It is for situations that base wants its children to implement functionality that the base itself needs to use. Imagine a silly example - cars.

class Car {
public:
    int getTorque();
    int getPower();

private:
    virtual const Engine& gimmeEngine() = 0;
};

class Ferrari : public Car {
private:
    FerrariEngine myCoolEngine;
    const Engine& gimmeEngine() { return myCoolEngine; }
};

Now Car doesn't need to know anything about Ferrari's engine, only that it implements some Engine interface that guaranties that Car can get the information about its power and torque.

In this silly example everything could be simplified by making getTorque and getPower pure virtual, but I hope it illustrates the idea. Base needs to use some specific logic it knows every child must have, so it queries it throught a private pure virtual member.



回答3:

If the method is virtual it can be overridden by derived classes, even if it's private. Anyway, it should be declared with protected.