Factory Method

Bill Baxter dnewsgroup at billbaxter.com
Wed Sep 19 13:19:50 PDT 2007


Klaus Friedel wrote:
> Im sure I missed something. I tried to create a factory class producing objects on the heap like I would in C++ or Java:
> 
> //**************************************
> class Cat{
>   int id;
> }
> 
> class CatFactory{
>   Cat * createCat(){
>     Cat aCat = new Cat();
>     return &aCat;
>   }
> }
> 
> void test(){
>   CatFactory factory = new CatFactory();
>   Cat *c1 = factory.create();
>   Cat *c2 = factory.create();
> }
> //**************************************************************
> 
> I discoverd this would not work because aCat will be allocated on the stack instead the heap.
> Why ???? Looks anything but intuitive to me.
> What would be the correct way to create a object on the GC controlled heap an return a reference to that object ?
> 
> Regards,
> 
> Klaus Friedel

Its more like Java than you were thinking. :-) With 'class' objects in D 
the pointer is implicit.  aCat = new Cat() *is* a reference.

// correct version
class Cat{
   int id;
}

class CatFactory{
   Cat createCat(){
     Cat aCat = new Cat();
     return aCat;
   }
}

void test(){
   CatFactory factory = new CatFactory();
   Cat c1 = factory.create();
   Cat c2 = factory.create();
}


structs aren't implicitly references though.  So to make a 'struct' 
factory you would need to have the pointer stuff.

--bb



More information about the Digitalmars-d mailing list