Why is this an issue?
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 both clearer and more sound to use derived class-specific specifiers instead: override
or
final
.
-
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
indicates that a function is intended to override a base-class function. The compiler will issue a warning if this is not
the case. It is redundant in combination with final
.
Noncompliant code example
class Counter {
protected:
int c = 0;
public:
virtual void count() {
c++;
}
};
class FastCounter: public Counter {
public:
virtual void count() { // Noncompliant
c += 2;
}
};
Compliant solution
class Counter {
protected:
int c = 0;
public:
virtual void count() {
c++;
}
};
class FastCounter: public Counter {
public:
void count() override {
c += 2;
}
};
or
class Counter {
protected:
int c = 0;
public:
virtual void count() {
c++;
}
};
class FastCounter: public Counter {
public:
void count() final {
c += 2;
}
};
Resources
Related rules