Is it recommended to explicitly make overriding functions virtual?

后端 未结 3 1304
面向向阳花
面向向阳花 2021-01-18 07:46

In times before C++11 when a virtual function was overriden in a derived class, it was recommended to add the virtual keyword also to the derived class function to make the

3条回答
  •  梦谈多话
    2021-01-18 08:23

    Yes, you should prefer to use override instead of virtual when overriding the base class behavior. Because it could lead to possible errors

    How could this possibly lead to errors? Here's an example,

    #include 
    using namespace std;
    
    class Base {
     public:
        virtual void foo() {
            std::cout << "BASE foo" << std::endl;
        }
        void bar() {
            std::cout << "BASE bar" << std::endl;
        }
    };
    
    
    class A : public Base{
     public:
        void foo() override {
            std::cout << "A foo" << std::endl;
        }
        virtual void bar() { 
            std::cout << "A bar" << std::endl;
        }
    };
    
    class B : public A {
     public:
        void bar() override { 
            std::cout << "B bar" << std::endl;
        }
    };
    
    
    int main(int argc, char *argv[])
    {
        B b;
        A *a = &b;
        Base *base = &b;
        base->foo();
        a->foo();
        base->bar();
        a->bar();
        return 0;
    }
    

    And the output would be

    A foo
    A foo
    BASE bar
    B bar
    

    foo() is overridden correctly but bar isn't and becomes hidden in some cases. The calls to bar() are not invoking the same method even though the underlying object is the same

    If we enforced ourselves to always use override when overriding and virtual only to define new virtual functions then when we try void bar() override {} the compiler complains error: ‘void A::bar()’ marked ‘override’, but does not override

    Which is exactly why the Autosar specification defines the following rule

    Rule A10-3-1 (required, implementation, automated) Virtual function declaration shall contain exactly one of the three specifiers: (1) virtual, (2) override, (3) final.

    Rationale: Specifying more than one of these three specifiers along with virtual function declaration is redundant and a potential source of errors.

提交回复
热议问题