How to init a static object ?

TSalm tsalm at free.fr
Sun Mar 16 04:22:05 PDT 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


More information about the Digitalmars-d-learn mailing list