Project

General

Profile

Actions

Bug #3857

closed

Rule 3.30 should NOT suggest to use virtual with final methods

Added by Davide Pesavento over 7 years ago. Updated over 7 years ago.

Status:
Closed
Priority:
Normal
Category:
Docs
Target version:
Start date:
Due date:
% Done:

100%

Estimated time:

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).

Actions #1

Updated by Davide Pesavento over 7 years ago

  • Status changed from New to Feedback

Waiting for feedback.

Actions #2

Updated by Alex Afanasyev over 7 years ago

+1

Actions #3

Updated by Junxiao Shi over 7 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.

Actions #4

Updated by Davide Pesavento over 7 years ago

  • Status changed from Feedback to Code review
  • % Done changed from 0 to 100
Actions #5

Updated by Davide Pesavento over 7 years ago

  • Status changed from Code review to Closed
Actions

Also available in: Atom PDF