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

后端 未结 5 1128
猫巷女王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:39

    Only the pure virtual methods have to be implemented in derived classes, but you still need a definition (and not just a declaration) of the other virtual methods. If you don't supply one, the linker might very well complain.

    So, just putting {} after your optional virtual method gives you an empty default implementation:

    class Abstract {
    public:
        virtual void foo() = 0; // pure virtual must be overridden
        virtual void bar() {}   // virtual with empty default implementation
    };
    
    class Derived : Abstract {
    public:
        virtual void foo();
    };
    

    A more involved default implementation would go into a separate source file though.

提交回复
热议问题