Implementing pure virtual function from abstract base class: does override specifier have any meaning?

前端 未结 4 414
执笔经年
执笔经年 2021-01-19 10:20

Background

I just stumbled over a use case of the override specifier that, as far as I can tell, seems redundant and also without any particular semantics meaning,

4条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-19 10:55

    Technically, both versions are syntactically correct and legal. The override specifier is mainly meant to prevent unexpected behavior. The compiler will throw an error as soon as it encounters a member function marked as override which is not actually overriding a virtual function. This may occur if, for some reason, you change the signature of the virtual base class function. Consider this example:

    class Abstract {
        virtual void foo() { ...}
    }; 
    
    class Derived : public Abstract {
        void foo() override { ... }
    };
    

    Now, if the signature of Abstract::foo is changed, let's say to

    class Abstract {
        virtual void foo(int bar) { ...}
    }; 
    

    the compiler will throw an error at Derived::foo as it no longer overrides a function of Abstract which it wouldn't without the override qualifier. This helps you to better maintain your code. However, in your specific case (i.e. with pure virtual declarations), an error would be thrown as well. So using override is mainly considered "good practice", I guess. More on that topic: http://en.cppreference.com/w/cpp/language/override

提交回复
热议问题