Factory Method

Klaus Friedel d at friedelprivat.de
Wed Sep 19 13:04:18 PDT 2007


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



More information about the Digitalmars-d mailing list