Thread overview
class creation in module scope?
Mar 21, 2007
Hendrik Renken
Mar 21, 2007
BCS
Mar 21, 2007
Derek Parnell
March 21, 2007
Hi,
i am having some trouble figuring out, why i cant instantiate my class within module-scope.

Problem:

### A.d File ###
module foo.A;

import foo.B;


public MyClass my = new MyClass();

/... some functions .../



### B.d File ###
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
March 21, 2007
Hendrik Renken wrote:
> Hi,
> i am having some trouble figuring out, why i cant instantiate my class within module-scope.
> 
> Problem:
> 
> ### A.d File ###
> 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();}
March 21, 2007
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