Auto keyword and when to use it

Jonathan M Davis newsgroup.d at jmdavisprog.com
Tue Aug 21 19:45:38 UTC 2018


On Tuesday, August 21, 2018 12:22:42 PM MDT QueenSvetlana via Digitalmars-d-
learn wrote:
> On Monday, 20 August 2018 at 17:55:11 UTC, JN wrote:
> > class Foo
> > {
> >
> >     auto bar;
> >
> > }
> >
> > because now the compiler doesn't know what type 'bar' is
> > supposed to be.
>
> Just to clarify, even if I set bar in the constructor, I can't
> declare it with auto first, correct? I would have to declare a
> specific type?

Yes. As Mike's excellent response explained, auto is simply used to indicate
that you're not providing the explicit type and that it should be inferred
from the direct initialization of the variable. Whenever an explicit type is
not provided for a variable when declaring it, you _must_ use direct
initialization so that the type can be inferred. You can't do something like
have the type of a member variable inferred from what the constructor is
doing. And code like

auto foo;

is never legal.

- Jonathan M Davis





More information about the Digitalmars-d-learn mailing list