Is it a valid recipe to say that if I write final (to a member function) one should not write virtual?
In a base class, final methods would make no sense:
struct Driver {
virtual void print();
};
If one would add final to print() this would defy the reason for polymorphism in the first place. So that would be useless (though possible).
When I derive from this class I can detect errors with final, but only without virtual:
struct KeyboardDriver : public Driver {
virtual void prynt() final; // Oops: typo, but compiler-ok
};
struct MouseDriver : public Driver {
void prynt() final; // Error: Hooray, compiler found my typo
};
The additional final for KeyboardDriver::prynt was legal. Because final only requires the member function to be virtual — the compiler lets this pass (FDIS 9.2p9).
But when I leave out the virtual the typo makes this function non-virtual — it overrides nothing, i.e. no virtual function. Therefore final without virtual serves the same purpose to this respect as override does.
Update: Is my analysis correct? Does the functionality of final without virtual include that one of override?
Your analysis is correct. Not marking a
finalmember asvirtualavoids declaring a new, non-overriden member and catches mistakes. However, since that’s the purpose ofoverride, it may be simpler to just usefinal override; then whether the member is markedvirtualor not won’t matter at all.