Virtual/pure virtual explained

后端 未结 12 1474
暖寄归人
暖寄归人 2020-11-22 01:31

What exactly does it mean if a function is defined as virtual and is that the same as pure virtual?

12条回答
  •  时光取名叫无心
    2020-11-22 02:29

    "Virtual" means that the method may be overridden in subclasses, but has an directly-callable implementation in the base class. "Pure virtual" means it is a virtual method with no directly-callable implementation. Such a method must be overridden at least once in the inheritance hierarchy -- if a class has any unimplemented virtual methods, objects of that class cannot be constructed and compilation will fail.

    @quark points out that pure-virtual methods can have an implementation, but as pure-virtual methods must be overridden, the default implementation can't be directly called. Here is an example of a pure-virtual method with a default:

    #include 
    
    class A {
    public:
        virtual void Hello() = 0;
    };
    
    void A::Hello() {
        printf("A::Hello\n");
    }
    
    class B : public A {
    public:
        void Hello() {
            printf("B::Hello\n");
            A::Hello();
        }
    };
    
    int main() {
        /* Prints:
               B::Hello
               A::Hello
        */
        B b;
        b.Hello();
        return 0;
    }
    

    According to comments, whether or not compilation will fail is compiler-specific. In GCC 4.3.3 at least, it won't compile:

    class A {
    public:
        virtual void Hello() = 0;
    };
    
    int main()
    {
        A a;
        return 0;
    }
    

    Output:

    $ g++ -c virt.cpp 
    virt.cpp: In function ‘int main()’:
    virt.cpp:8: error: cannot declare variable ‘a’ to be of abstract type ‘A’
    virt.cpp:1: note:   because the following virtual functions are pure within ‘A’:
    virt.cpp:3: note:   virtual void A::Hello()
    

提交回复
热议问题