Pure virtual function with implementation

前端 未结 9 2083
长发绾君心
长发绾君心 2020-11-22 10:10

My basic understanding is that there is no implementation for a pure virtual function, however, I was told there might be implementation for pure virtual function.

9条回答
  •  故里飘歌
    2020-11-22 11:00

    If you have code that should be executed by the deriving class, but you don't want it to be executed directly -- and you want to force it to be overriden.

    Your code is correct, although all in all this isn't an often used feature, and usually only seen when trying to define a pure virtual destructor -- in that case you must provide an implementation. The funny thing is that once you derive from that class you don't need to override the destructor.

    Hence the one sensible usage of pure virtual functions is specifying a pure virtual destructor as a "non-final" keyword.

    The following code is surprisingly correct:

    class Base {
    public:
      virtual ~Base() = 0;
    };
    
    Base::~Base() {}
    
    class Derived : public Base {};
    
    int main() { 
      // Base b; -- compile error
      Derived d; 
    }
    

提交回复
热议问题