Do ALL virtual functions need to be implemented in derived classes?

后端 未结 5 1108
猫巷女王i
猫巷女王i 2020-11-30 18:44

This may seem like a simple question, but I can\'t find the answer anywhere else.

Suppose I have the following:

class Abstract {
public:
    virtual          


        
5条回答
  •  温柔的废话
    2020-11-30 19:27

    Derived classes do not have to implement all virtual functions themselves. They only need to implement the pure ones.1 That means the Derived class in the question is correct. It inherits the bar implementation from its ancestor class, Abstract. (This assumes that Abstract::bar is implemented somewhere. The code in the question declares the method, but doesn't define it. You can define it inline as Trenki's answer shows, or you can define it separately.)


    1 And even then, only if the derived class is going to be instantiated. If a derived class is not instantiated directly, but only exists as a base class of more derived classes, then it's those classes that are responsible for having all their pure virtual methods implemented. The "middle" class in the hierarchy is allowed to leave some pure virtual methods unimplemented, just like the base class. If the "middle" class does implement a pure virtual method, then its descendants will inherit that implementation, so they don't have to re-implement it themselves.

提交回复
热议问题