What's the correct way of creating an instance of class in D?

Mike Parker aldacron at gmail.com
Thu Nov 3 06:02:13 UTC 2022


On Thursday, 3 November 2022 at 05:41:06 UTC, Siarhei Siamashka 
wrote:

> Thanks for the link and also thanks for confirming that you 
> have no clue what's going on. I think that what actually

That's not necessary. He does know what's going on and pointed 
you to the correct place. The second paragraph on the page says:

> Class objects are instantiated by reference only.

Then further down the page:

https://dlang.org/spec/class.html#class-instantiation

> Instances of class objects are created with a NewExpression:


> happens is that the D code
>
> ```D
>   A a2;
>   a2.foo();
> ```
>
> is roughly equivalent to C++
>
> ```C++
>   A *a2 = NULL;
>   a2->foo();
> ```
>

That's correct. Classes in D are like Java classes. `a2` is a 
reference. Structs, on the other hand, are value types as they 
are in C++. D enforces the distinction that C++


> I see two problems here. First, the D language documentation is 
> incomplete and does not cover this particular syntax. And

I think that it does. But given that you missed it, then it could 
potentially be improved. Perhaps a new entry in the instantiation 
section that makes clear a declaration without an initialization 
is default initialized to null.

The documentation is maintained by the community. You can post 
about issues you find here in the forums, or better, report them 
at issues.dlang.org (we're moving our bug tracking to GitHub 
soon).

> second, D language is designed (intentionally or accidentally) 
> to be hostile to the C++ developers trying to learn it. This 
> particular issue is known as 
> https://en.wikipedia.org/wiki/False_friend

  D is not C++. Nor is it Java, nor C, nor C#, nor Python, etc. 
There are similarities and differences. Any time you try out a 
language, you will view it through the lens of the language(s) 
you know, and you are going to encounter problems like this. I 
wouldn't call that hostility, intentional or accidental.

But when you do encounter those differences in D, people here are 
willing to help you, so all you have to do is ask.


More information about the Digitalmars-d-learn mailing list