Pure virtual function with implementation

前端 未结 9 2120
长发绾君心
长发绾君心 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:02

    A pure virtual function must be implemented in a derived type that will be directly instantiated, however the base type can still define an implementation. A derived class can explicitly call the base class implementation (if access permissions allow it) by using a fully-scoped name (by calling A::f() in your example - if A::f() were public or protected). Something like:

    class B : public A {
    
        virtual void f() {
            // class B doesn't have anything special to do for f()
            //  so we'll call A's
    
            // note that A's declaration of f() would have to be public 
            //  or protected to avoid a compile time problem
    
            A::f();
        }
    
    };
    

    The use case I can think of off the top of my head is when there's a more-or-less reasonable default behavior, but the class designer wants that sort-of-default behavior be invoked only explicitly. It can also be the case what you want derived classes to always perform their own work but also be able to call a common set of functionality.

    Note that even though it's permitted by the language, it's not something that I see commonly used (and the fact that it can be done seems to surprise most C++ programmers, even experienced ones).

提交回复
热议问题