Summary: you have to new objects. Always.
D's classes are closer to C# or Java than C++. Specifically, objects are always, always reference values.
MyObject is, under the hood, a pointer to the actual object. Thus, when you use MyObject obj;
, you're creating a null
pointer, and have not, in fact, created an object. An object must be created using the new
operator:
auto obj = new Object();
This creates obj on the heap.
You cannot directly construct objects on the stack in D. The best you can do is something like this:
scope obj = new MyObject;
The compiler is allowed to place the object on the stack, but doesn't have to.
(Actually, I suspect this might be going away in a future version of D2.)
On a side note, if you are using D2, then I believe your main function should look like this:
int main(string[] args)
{
...
}
char[]
and string
have the same physical layout, but mean slightly different things; specifically, string
is just an alias for immutable(char)[]
, so by using char[]
you're circumventing the const system protections.