C++ Logo


Advanced search

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

From: Arthur O'Dwyer <arthur.j.odwyer_at_[hidden]>
Date: Tue, 2 May 2023 11:08:42 -0400
This is Clang's `-Wsuggest-override`. I always turn it on and keep my
codebase clean of its warnings. No change to the Standard required.

On Tue, May 2, 2023 at 10:21 AM Frederick Virchanza Gotham via
Std-Proposals <std-proposals_at_[hidden]> wrote:

> 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.
> --
> Std-Proposals mailing list
> Std-Proposals_at_[hidden]
> https://lists.isocpp.org/mailman/listinfo.cgi/std-proposals

Received on 2023-05-02 15:08:55