c++ - Implementing pure virtual function from abstract base class: does override specifier have any meaning? -
background
i stumbled on use case of override
specifier that, far can tell, seems redundant , without particular semantics meaning, maybe i'm missing something, hence question. before proceeding, should point out i've tried find answer here on so, nearest got following threads, not answering query (maybe can point out q&a answers question).
question
consider following abstract class:
struct abstract { virtual ~abstract() {}; virtual void foo() = 0; };
is there reason use override
specifier when implementing foo()
in non-abstract class derived directly abstract
(as in derivedb
below)? i.e., when implementation of foo()
required derived class non-abstract (and not overriding anything)?
/* "common" derived class implementation, in personal experience (include virtual keyword semantics) */ struct deriveda : public abstract { virtual void foo() { std::cout << "a foo" << std::endl; } }; /* there reason having override specifier here? */ struct derivedb : public abstract { virtual void foo() override { std::cout << "b foo" << std::endl; } };
i'm not big fan of override
, but, assuming it's find useful in general, then, yes, putting override
on virtual function overrides pure virtual functions useful. consider rather contrived example:
struct base { virtual void f() = 0; }; struct derived : base { virtual void f(); virtual void f(int); };
now suppose maintainer of base
(perhaps future self) changes base
this:
struct base { virtual void f(int) = 0; };
now behavior of derived
has quietly changed. override
compiler report error.
Comments
Post a Comment