www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - How to init a static object ?

reply TSalm <tsalm free.fr> writes:
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
Mar 15 2008
parent reply Kirk McDonald <kirklin.mcdonald gmail.com> writes:
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
Mar 15 2008
parent TSalm <tsalm free.fr> writes:
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
Mar 16 2008