I am converting a bunch of code from C++ in to C. Is there an equivalent pattern in C for a Object factory?
Consider the following source code. Based on a parameters (int type) the ObjectFactory() function should return a void pointer to an struct of a pedicure type. How can I instantiate the struct in a way that I can have a pointer to it after the function returns.
typedef struct {
unsigned int a;
unsigned int b;
unsigned int c;
} CThings ;
typedef struct {
unsigned int d;
unsigned int e;
unsigned int f;
} CPlaces ;
void * ObjectFactory( int type ) {
switch( type ) {
case 5 : {
return ??? CPlaces ;
break;
}
case 35 : {
return ??? CThings ;
break;
}
default: {
// unknown type
return NULL ;
}
}
return NULL ;
}
int _tmain(int argc, _TCHAR* argv[])
{
void * p = ObjectFactory( 5 );
// Do soemthing with the pointer.
CPlaces * places = (CPlaces*) p ;
places->d = 5 ;
places->e = 6 ;
places->f = 7 ;
return 0;
}
How about using
malloc:No need for the
breakif you already return. If you like, you can add some initialization before returning.The caller will have to know the actual type so she can cast the pointer back to the correct type. This will probably amount to a duplicate switch statement at the caller’s site.