In a base class, virtual indicates that a function can be overridden. In a derived class, it indicates an override. But given the
specifier’s dual meaning, it would be clearer and more sound to use derived class-specific specifiers instead: override or
final.
class Counter {
protected:
int c = 0;
public:
virtual void count() {
c++;
}
};
class FastCounter: public Counter {
public:
virtual void count() { // Noncompliant: ambiguous
c += 2;
}
};
-
override indicates that a function is intended to override a base-class function. The compiler will issue a warning if this is not
the case.
class FastCounter: public Counter {
public:
void count() override {
c += 2;
}
};
-
final indicates a function override that cannot itself be overridden. The compiler will issue a warning if the
signature does not match the signature of a base-class virtual function. override is redundant when final is
specified.
class FastCounter: public Counter {
public:
void count() final {
c += 2;
}
};