Thread overview
How to init a static object ?
Mar 15, 2008
TSalm
Mar 15, 2008
Kirk McDonald
Mar 16, 2008
TSalm
March 15, 2008
Hi all,

I would do something like this below, but DMD return me the error :
  testStaticInit.d(10): Error: non-constant expression new A
on the line "public static A a=new A();"
Is there a simple way to instanciate a static class ?



class A
{
 public this() {}
}

class B
{
 public static A a = new A();

 public this() {}

}

void main()
{
 new B();
}



 Thanks in advance,
 TSalm


March 15, 2008
TSalm wrote:
> Hi all,
> 
> I would do something like this below, but DMD return me the error :
>   testStaticInit.d(10): Error: non-constant expression new A
> on the line "public static A a=new A();"
> Is there a simple way to instanciate a static class ?
> 
> 
> 
> class A
> {
>  public this() {}
> }
> 
> class B
> {
>  public static A a = new A();
> 
>  public this() {}
> 
> }
> 
> void main()
> {
>  new B();
> }
> 
> 
> 
>  Thanks in advance,
>  TSalm
> 
> 

(One incidental note: Your use of 'public' is unnecessary, as everything is public by default in D.)

Use a static constructor:

class A {}

class B {
    static A a;
    static this() {
        a = new A;
    }
}

-- 
Kirk McDonald
http://kirkmcdonald.blogspot.com
Pyd: Connecting D and Python
http://pyd.dsource.org
March 16, 2008
On Sat, 15 Mar 2008 11:57:00 -0800, Kirk McDonald wrote:

> TSalm wrote:
>> I would do something like this below, but DMD return me the error :
>>   testStaticInit.d(10): Error: non-constant expression new A
>> on the line "public static A a=new A();" Is there a simple way to
>> instanciate a static class ?
>> 
>> 
>> 
>> class A
>> {
>>  public this() {}
>> }
>> 
>> class B
>> {
>>  public static A a = new A();
>> 
>>  public this() {}
>> 
>> }
>> 
>> void main()
>> {
>>  new B();
>> }
>> 
>> 
>> 
> (One incidental note: Your use of 'public' is unnecessary, as everything
> is public by default in D.)

Thanks. Moreover, IMHO, it's a good things since the majority of method declarations are public.


> 
> Use a static constructor:
> 
> class A {}
> 
> class B {
>      static A a;
>      static this() {
>          a = new A;
>      }
> }

Great, like this, it's possible to bring in some algorithms in this static constructor. Also, IMHO, it could have to be nice to be able to instanciate it in the declaration line...

Thanks!
TSalm