Why does this compile (method in class without return type)

Jacob Carlborg via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed May 3 00:37:31 PDT 2017


On 2017-05-03 08:54, nkm1 wrote:
> Consider:
>
> import std.stdio;
>
> class A
> {
>      final print() { writeln(this); } // no return type
> }
>
> class B : A
> {
>      final void print() { writeln(this); }
> }
>
> void main()
> {
>      auto b = new B;
>      b.print();
>
>      A a1 = b;
>      a1.print();
>
>      A a2 = new A;
>      a2.print();
> }
>
> That compiles:
>
> $ dmd -de -w -g ./main.d
> $ main
> main.B
> main.B
> main.A
>
> with dmd 2.074 on linux:
>
> $ dmd --version
> DMD64 D Compiler v2.074.0
> Copyright (c) 1999-2017 by Digital Mars written by Walter Bright
>
> Is that a bug? (in the compiler). I'm learning D, and I'm half way
> through Andrei's book; I also read the documentation (on D's website)
> and I think that shouldn't compile?

It might be by accident but I think the compiler is inferring the return 
type. Just as "auto" is not necessary to infer the type of a variable if 
there's another attribute:

auto a = 3;
const auto b = 4; // here "auto" is redundant
const c = 5;

In your case you have "final" as the attribute.

-- 
/Jacob Carlborg


More information about the Digitalmars-d-learn mailing list