Date: Sat, 15 Aug 2020 13:00:40 +0300
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.
> 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.
Received on 2020-08-15 05:04:11