Should I reuse virtual when overridden in a sub-subclass?

I know that I don't need to declare the overriding function in the subclass as virtual

. But if I use a virtual function in a sub-subclass, I need to declare the subclass function as virtual

?

struct Base
{
    virtual int foo();
};

struct Derived : Base
{
    virtual int foo() override
    {
       // ...
    }
};

struct DoubleDerived : Derived
{
    int foo() override
    {
       // ...
    }
};

      

+3


source to share


2 answers


I just found a Core guideline C.128 which says:



Virtual functions should specify exactly one of virtual, override, or final.

      

0


source


You don't need the function to be virtual anyway, but it makes it clearly clear. Previously (before it override

was available) you could override some function, and then if the function was changed in the base class, your derived class will no longer override it and the code will compile without any problem. Your function in the derived class will not override anything and will become non-virtual.



Since the override

compiler will prevent such errors, and the function cannot magically become non-virtual if the base is changed. In other words, if override or final , the function is assumed to be virtual , otherwise it would be a compilation error.

+4


source







All Articles