Thread overview
class array
Mar 20, 2007
orgoton
Mar 20, 2007
Deewiant
Mar 20, 2007
BCS
March 20, 2007
I created a class and now I want to create an array (at compile time) so I did

public myClass myArray[]=new myClass(5);

It didn't compile because of the parameters, so I changed to

public myClass myArray[]=new myClass()(5);

Since myClass ctor doesn't take parameters. It mentioned that was expecting ";" and found "(" so I tried the C++ way

public myClass myArray[]=new[5] myClass();

Then again, "[" wasn't expected. How do I then construct 5 objects?
March 20, 2007
orgoton wrote:
> I created a class and now I want to create an array (at compile time) so I did
> 
> public myClass myArray[]=new myClass(5);
> 
> It didn't compile because of the parameters, so I changed to
> 
> public myClass myArray[]=new myClass()(5);
> 
> Since myClass ctor doesn't take parameters. It mentioned that was expecting ";" and found "(" so I tried the C++ way
> 
> public myClass myArray[]=new[5] myClass();
> 
> Then again, "[" wasn't expected. How do I then construct 5 objects?

public myClass[] myArray = new myClass[5];

or the equivalent

public myClass[] myArray = new myClass[](5);

Note that the D-style declaration syntax myClass[] myArray is generally preferred over the C-style myClass myArray[].

Also note that this generates just the array: each class reference within the array will be null until initialized, for instance like so:

foreach (inout c; myArray)
	c = new myClass();
March 20, 2007
Reply to Deewiant,

> public myClass[] myArray = new myClass[5];
> 

Also note that this is an array of class /references/ not objects.

Just thought that should be explicitly stated.