Bug #3857
closedRule 3.30 should NOT suggest to use virtual with final methods
100%
Description
Compare the following (this is with clang, gcc gives similar output):
$ clang++ -xc++ -std=c++11 -c -o /dev/null - <<_EOF_
class A
{
virtual void foo();
};
class B : public A
{
void fooo() final; // typo in function name
};
_EOF_
<stdin>:8:15: error: only virtual member functions can be marked 'final'
void fooo() final;
^~~~~
1 error generated.
$ clang++ -xc++ -std=c++11 -c -o /dev/null - <<_EOF_
class A
{
virtual void foo();
};
class B : public A
{
virtual void fooo() final; // typo, but this time the function is also marked virtual
};
_EOF_
$ # no errors!
Note in the example above that when virtual
is used on a function that is also marked final
(because it's supposed to be the final override of a virtual method), the compiler doesn't raise any errors. One of the major reasons to use final
is precisely to catch this kind of mistakes (they can be much less obvious than a simple typo), however rule 3.30 nullifies this advantage by suggesting to still use virtual
alongside final
.
I propose to adopt either of the following solutions:
A. Prohibit using virtual
on final methods. For consistency, the same should apply to methods marked override
as well.
B. Recommend to always use override
in conjunction with final
.
I prefer solution A, because B would lead to excessive code verbosity for no reason (we'd have to use "virtual void foo() final override
" all the time).