C++: Private virtual functions vs. pure virtual functions [duplicate]

妖精的绣舞 提交于 2019-12-03 14:45:27

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.

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.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!