specifying object type at compile time
-
given a class heirarch where A is the base class and B , C are derived classes . Now I want to implement something like an object factory externally where I want to automatically create an object of the appropriate type . For this I define a struct with the definition ( pardon me for the pseudo code as part of the problem is with usage)
typedef struct { int code ; reference_to_type_creator ; }OBJ_TYPE ; OBJ_TYPE objTable[] = { objA_code , < reference to create an object of type A > } , { objB_code , < reference to create an object of type B > } , { objC_code , < reference to create an object of type C > } , { -1 , NULL }
such that I can use this table in a function that processes random object entries
ProcessObject( int objCode ) { for (int i=0;objTable[i].code!=-1;i++) { if( objCode == objTable[i].code) { A *a = objTable[i].reference_to_type_creator // Unsure about how this could work a->Foo() } } }
I was unclear as to how this reference would be specified in the struct array above and its usage. Help is appreciated }
Engineering is the effort !
-
given a class heirarch where A is the base class and B , C are derived classes . Now I want to implement something like an object factory externally where I want to automatically create an object of the appropriate type . For this I define a struct with the definition ( pardon me for the pseudo code as part of the problem is with usage)
typedef struct { int code ; reference_to_type_creator ; }OBJ_TYPE ; OBJ_TYPE objTable[] = { objA_code , < reference to create an object of type A > } , { objB_code , < reference to create an object of type B > } , { objC_code , < reference to create an object of type C > } , { -1 , NULL }
such that I can use this table in a function that processes random object entries
ProcessObject( int objCode ) { for (int i=0;objTable[i].code!=-1;i++) { if( objCode == objTable[i].code) { A *a = objTable[i].reference_to_type_creator // Unsure about how this could work a->Foo() } } }
I was unclear as to how this reference would be specified in the struct array above and its usage. Help is appreciated }
Engineering is the effort !
i'd just do it with a switch
ProcessObject( int objCode )
{
A* a = NULL;
switch (objCode)
{
case 0:
a = new whatever0;
break;
case 1:
a = new whatever1;
break;
etc..
}
a->Foo();
}otherwise, maybe you could add static Create methods to your object types, and put refs to those in your array (off the top of my head):
class whatever0 : public A
{
static public whatever0 * Create()
{
return new whatever0();
}
...
};
class whatever1 : public A
{
static public whatever1 * Create()
{
return new whatever1();
}
...
};...
OBJ_TYPE objTable[] =
{
{0, whatever0::Create},
{1, whatever1::Create},
};... where OBJ_TYPE is a struct with an int and a function pointer that returns an A*
you'd need the static Create functions because you can't do function pointers to non-static member classes.