Requiring virtual function overrides to use override keyword

Barry picture Barry · Mar 19, 2015 · Viewed 18k times · Source

C++11 added override to ensure that member functions you write that you intend to override base-class virtual functions actually do (or won't compile).

But in a large object hierarchy, sometimes you could accidentally end up writing a member function that overrides a base-class virtual when you didn't intend it! For instance:

struct A {
    virtual void foo() { }  // because obviously every class has foo().
};

struct B : A { ... };

class C : B {
private:
    void foo() {
        // was intended to be a private function local to C
        // not intended to override A::foo(), but now does
    }
};

Is there some compiler flag/extension that would at least issue a warning on C::foo ? For readability and correctness, I just would like to enforce that all overrides use override.

Answer

Barry picture Barry · Apr 26, 2015

Looks like the GCC 5.1 release added exactly the warning I was looking for:

-Wsuggest-override
       Warn about overriding virtual functions that are not marked with the override keyword.

Compiling with -Wsuggest-override -Werror=suggest-override would then enforce that all overrides use override.