dfri dfri - 3 months ago 12
C++ Question

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

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, but maybe I'm missing something, hence this question. Before proceeding, I should point out that I've tried to find an answer to it here on SO, but the nearest I got were the following threads, not really answering my query (maybe someone can point out a Q&A that actually already answers my question).



Question



Consider the following abstract class:

struct Abstract {
virtual ~Abstract() {};
virtual void foo() = 0;
};


Is there any reason to use the
override
specifier when implementing
foo()
in a non-abstract class derived directly from
Abstract
(as in
DerivedB
below)? I.e., when the implementation of
foo()
is already required for the derived class to be non-abstract (and not really overriding anything)?

/* "common" derived class implementation, in my personal experience
(include virtual keyword for semantics) */
struct DerivedA : public Abstract {
virtual void foo() { std::cout << "A foo" << std::endl; }
};

/* is there any reason for having the override specifier here? */
struct DerivedB : public Abstract {
virtual void foo() override { std::cout << "B foo" << std::endl; }
};

Answer

I'm not a big fan of override, but, assuming it's something that you find useful in general, then, yes, putting override on a virtual function that overrides a pure virtual functions is useful. Consider this rather contrived example:

struct Base {
    virtual void f() = 0;
};

struct Derived : Base {
    virtual void f();
    virtual void f(int);
};

Now suppose that the maintainer of Base (perhaps even your future self) changes Base to look like this:

struct Base {
    virtual void f(int) = 0;
};

Now the behavior of Derived has quietly changed. With override the compiler would report an error.