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).
Updated by Davide Pesavento about 8 years ago
- Status changed from New to Feedback
Waiting for feedback.
Updated by Junxiao Shi about 8 years ago
I agree with forbidding virtual
on final
methods. Suggested wording:
Annotate with override
or final
when overriding a virtual method or destructor.
virtual
MUST NOT be used along with final
, so that compiler can generate an error when a final
function does not override.
virtual
SHOULD NOT be used along with override
, for consistency with final
.
Updated by Davide Pesavento almost 8 years ago
- Status changed from Feedback to Code review
- % Done changed from 0 to 100
Updated by Davide Pesavento almost 8 years ago
- Status changed from Code review to Closed