Object.factory

Deewiant deewiant.doesnotlike.spam at gmail.com
Thu Jun 7 12:03:50 PDT 2007


Arlen wrote:
> There was the 'factory' static method introduced in D some time ago. I haven't been succeeding in creating a single instance of any of my classes. The result of the function call is always 'null'.
> 
> What's going on?
> 
> An example code:
> 
> ---------------------------------------------
> import std.stdio;
> 
> alias char[] string;
> 
> int main(string[] args)
> {
> 	MyClass a = cast(MyClass) Object.factory("MyClass");
> 
> 	if(a !is null)
> 	{
> 		a.name = "Arlen";
> 		a.family_name = "Keshabyan";
> 
> 		writefln(a.name ~ " " ~ a.family_name);
> 	}
> 	else
> 		writefln("cannot create the MyClass class instance!");
> }
> 
> 
> 
> class MyClass
> {
> private:
> 
>     string m_name;
>     string m_family_name;
> 
> public:
> 
>     this()
>     {
>     	m_name = "";
>     	m_family_name = "";
>     }
> 
>     string name(){return m_name;}
>     void name(string value){m_name = value;}
> 
>     string family_name(){return m_family_name;}
>     void family_name(string value){m_family_name = value;}
> }
> 
> 

You need to specify the fully qualified name, i.e. precede "MyClass" with the
module name and a period.

For instance, if your code is in a file called foo.d, or you have a "module
foo;" in the code, pass "foo.MyClass" to Object.factory.

Note that if you know the class name at compile time, you don't need
Object.factory: you can use a mixin statement instead, which works just as you'd
expect and without runtime costs:

mixin("MyClass a = new MyClass;");

-- 
Remove ".doesnotlike.spam" from the mail address.



More information about the Digitalmars-d mailing list