C++ Logo

std-proposals

Advanced search

[std-proposals] enable very strict use of 'virtual', 'override', etc.

From: Frederick Virchanza Gotham <cauldwell.thomas_at_[hidden]>
Date: Tue, 2 May 2023 15:21:05 +0100
Right now in my day job I'm trying to fix a bug that was introduced by
my predecessor. The code is C++ for a microcontroller. There is an
abstract base class, 'Motor'. Derived from that is 'FPGAMotor'.
Derived from that is 'StageMotor'.

Now I think over the years we're all guilty of taking a short cut
rather than re-writing a class hierarchy properly. It turns out that a
lot of the FPGA stuff is actually in the base class, 'Motor', even
though a totally unrelated kind of motor could potentially inherit
from 'Motor'. I'm guessing that my predecessor just saw a quick fix
rather then spending hours re-arranging that class hiearchy.

Now that I need to debug the code, I'm refactoring it and re-writing
the hierarchy properly. Every time I see a method defined inside a
class, there are a few possibilities:

(1) The method is not inherited and is intended to be virtual
(2) The method is not inherited and is not intended to be virtual
(3) The method is inherited, and so it should be virtual in the base class(es)
(4) The method is inherited, and is expected to have no prior
definition (i.e. it's expected to be pure virtual in the base
class(es))
(5) The method is inherited, but it's not virtual in the base class
and isn't intended to be virtual in the derived class either.

Scenario No. 5 is usually a red flag, and I wish the compiler would disallow it.
Scenario No. 1 and No. 2 are both valid and common.
Scenario No. 3 is the most common (this is what the 'override' keyword is for)
Scenario No. 4 is less common than No. 3 but is still valid

Without breaking existing code, I'd like if a class could have a
'strict' mode, something like:

    class MyClass strict {

    };

When a class is written in 'strict' mode, each of the scenarios
described above must have the following or else you get a compiler
error.
Scenario 1) must be prefixed with 'new virtual'
Scenario 2) must be prefixed with 'new !virtual'
Scenario 3) must be prefixed with 'virtual', and also must be
postfixed with 'override'
Scenario 4) must be prefixed with 'virtual', and also must be
postfixed with 'override(0)'
Scenario 5) must be prefixed with '!virtual" and must be postfixed
with 'override(!virtual)'

If the compiler would enforce these rules, it would be easier to clean
up old code.

Received on 2023-05-02 14:21:18