www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - class creation in module scope?

reply Hendrik Renken <funsheep gmx.net> writes:
Hi,
i am having some trouble figuring out, why i cant instantiate my class 
within module-scope.

Problem:


module foo.A;

import foo.B;


public MyClass my = new MyClass();

/... some functions .../




module foo.B;


class MyClass
{
     /... some functions .../
}


bud (using gdc) complains:
foo/A.d:6: Error: non-constant expression new MyClass


what am i doing wrong. thought this little example would be the same as 
on the Reference-Page on digitalmars.com

thanks for you help,
hendrik
Mar 21 2007
parent reply BCS <BCS pathlink.com> writes:
Hendrik Renken wrote:
 Hi,
 i am having some trouble figuring out, why i cant instantiate my class 
 within module-scope.
 
 Problem:
 

 module foo.A;
 
 import foo.B;
 
 
 public MyClass my = new MyClass();
 
[...]
 
 bud (using gdc) complains:
 foo/A.d:6: Error: non-constant expression new MyClass
 
 
 what am i doing wrong. thought this little example would be the same as 
 on the Reference-Page on digitalmars.com
 
 thanks for you help,
 hendrik
new is a non-constant expression, and thay are not allowed at module scope. Use a static constrctor public MyClass my; static this(){my = new MyClass();}
Mar 21 2007
parent Derek Parnell <derek nomail.afraid.org> writes:
On Wed, 21 Mar 2007 14:06:16 -0800, BCS wrote:

 Use a static constrctor ...
Also known as a Module constructor so as not to be confused with a class constructors (at least in my mind). Module constructors are executed at run time before main() gets control. If you have import multiple modules with module constructors, they are executed in the order of the import statements. Beware of dependencies between modules as this can cause DMD to fail if recursive modules contain constructors. -- Derek (skype: derek.j.parnell) Melbourne, Australia "Justice for David Hicks!" 22/03/2007 9:54:54 AM
Mar 21 2007