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

前端 未结 4 418
执笔经年
执笔经年 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:57

    In case of pure virtual functions and compilations not really. You will get an error anyway (except in as in the example from Pete)

    But the error message may be more readable if you get an error like "your function does not override anything" compared to later "cannot instantiate abstract class"

    Another advantage would be while reading the declaration you know this is a derived method from a base class.

    Also it is good practice to just get used to declare all overridden methods with override. So why make a difference here and have inconsistent style.

    As to why it is good to have all overriden methods be declared override:

    imagine you have

    class A
    {
        virtual void Foo();
    };
    
    class B: public A
    {
        virtual void Foo() override;
    };
    

    And then you change Foo to a const function in A. Without override this will compile but when you call A->foo() and it is a B object B->foo() will not be called without any indication something changed there. With override you get an error here.

提交回复
热议问题