Nested sibling classes

Steven Schveighoffer schveiguy at gmail.com
Thu Jan 12 18:36:32 UTC 2023


On 1/12/23 12:05 PM, seany wrote:

> How can I make it, that classes b and c can access each other, and 
> create instances of each other freely? Thank you.
> 

So to just point out something that wasn't discussed by Salih:

When you declare a field of a class with an initializer, *that 
initializer is run at compile-time*. Which means, that even if it did 
work, every instance of every b would start out with the same exact `C` 
object (not a copy, the same one).

This is different than many other languages which treat initializers as 
part of the constructor (and run when you initialize a class). In D, the 
bits are simply copied into the new memory as the default state.

For this reason you should almost *never* initialize a class reference 
in a non-static field. Consider that if you ever modified that instance 
named `C`, all new instances of `b` would have a reference to that 
modified instance!

The reason the compiler doesn't like it is because it doesn't know how 
to initialize a `c` at compile time, since it needs the context pointer 
to the outer class.

Just moving initialization into the constructor should fix the problem, 
you don't need to make them static. Now, maybe you didn't intend to have 
a nested class with a reference to the outer class, and in that case, 
you should make it static.

-Steve


More information about the Digitalmars-d-learn mailing list