parsley72
parsley72

Reputation: 9057

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

I know I don't need to declare an overriding function in a subclass as virtual. But if I'm using a virtual function in a sub-subclass do 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
    {
       // ...
    }
};

Upvotes: 3

Views: 112

Answers (2)

parsley72
parsley72

Reputation: 9057

I just found Core guideline C.128 that states:

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

Upvotes: 0

Pavel P
Pavel P

Reputation: 16843

You don't have to, the function is virtual anyways, but it makes it unquestionably clear. Previously (before override was available) you could override some function and then if the function was changed in base class your derived class wouldn't override it anymore and the code would compile without any issues. Your function in derived class wouldn't override anything and would become non-virtual.

With override compiler will prevent this kind of mistakes and the function cannot magically become non-virtual if base is changed. In other words, if override or final is used, it's implied that the function is virtual, it would be compilation error otherwise.

Upvotes: 4

Related Questions