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

Also available in: Atom PDF