C++ Logo

STD-DISCUSSION

Advanced search

Subject: Re: Why no implicit declaration of necessary overrides in final classes?
From: Andrey Semashev (andrey.semashev_at_[hidden])
Date: 2020-08-15 05:00:40


On 2020-08-15 12:01, Eyal Rozenberg via Std-Discussion wrote:
> Consider the following code:
> ```
> class A {
>     virtual int foo() = 0;
> };
>
> class B final : A {
>     int foo() override; // (*)
> };
>
> int B::foo() { return 123; }
> ```
> ... which fails to compile if we remove the declaration (*).
>
> Since `B` is a final class, it must necessarily have all methods defined
> immediately or by inheritance. Specifically, we must define all `B`
> methods which are not defined for its (single) base class `A`.
>
> Why, then, must `B` declare `foo()` explicitly? Why is the implicit need
> for the definition not sufficient to allow this code to compile? I mean,
> I assume the standard requires an explicit declaration here, but what is
> the rationale for this requirement?
>
> An obvious counter-rationale is DRY: If class A has N virtual methods
> and M final subclasses, we'll have to write M*N redundant declarations.
> And these redundant declarations also visually "mask", to some extent,
> the declarations of those methods which are specific to B.

A counter-example:

   class A {
        virtual int foo() = 0;
   };

   class B : A {
        int foo() override;
   };

   class C final : B {
   };

   C* p = new C();
   p->foo();

If the declaration of C::foo was implicit, the compiler would have
mistakenly generated a call to C::foo even if it doesn't exist.


STD-DISCUSSION list run by std-discussion-owner@lists.isocpp.org

Older Archives on Google Groups