Auto keyword and when to use it

QueenSvetlana svetlanalilyrosemond at gmail.com
Tue Aug 21 18:18:25 UTC 2018


On Tuesday, 21 August 2018 at 16:15:32 UTC, XavierAP wrote:
>Only if someone
> likes "Type x = new Type()" instead of "auto x = new Type()" I 
> would say they're clearly wrong.

As you stated it's up to the programmer to decided. I'm in favor 
of Type x = new Type() because when it comes to constructing a 
class it usually means more code to verify the types, for example:


class Person {
   auto firstName;
   auto lastName;

   // constuctor to set first and last names

}

The compiler doesn't know know what firstName or lastName is 
supposed to be and a programmer might make the obvious assumption 
and use them as strings.

Doing this also means you have reject any type that isn't a 
string which means a private function to check the type that was 
pass to the constructor before initializing it. Where as if you 
declared it as a string to start of with, all you have to ensure 
is that it's not blank or contain illegal characters.

As the answer stated above doing what I showed in my example 
isn't allowed and this is where Python gets frustrating, because 
at any point the types could change. They introduced type hints, 
but it's not enforced, it just makes it more readable, you still 
have to write code to ensure the proper types were passed.


More information about the Digitalmars-d-learn mailing list