Factory Method

Nathan Reed nathaniel.reed at gmail.com
Wed Sep 19 13:22:57 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 ?

In D, classes are reference types.  This means when you declare a 
variable like "Cat aCat", that is really a reference to a Cat, and is 
allocated on the heap, not the stack.  So, the correct way to do this 
would be:

class CatFactor {
   Cat createCat () {
     return new Cat;
   }
}

The function allocates a Cat and returns a reference to it.  Pointers 
are not necessary.

Thanks,
Nathan Reed



More information about the Digitalmars-d mailing list