I know that maybe it's not the proper title, but I have some difficulties to understand how to explain the problem in a short line.
Basically I'm creating a framework with an high level of abstraction. I'm searching a decent way to create an initialization part where I describe how every object should works and a way to get that description to create the object from the index specified. I need to create some complex objects with the same structure but with different attributes. I have found a way but it seems not efficient:
#include <stdio.h>
class IObject
{
public:
virtual IObject* Create() = 0;
virtual void Main() = 0;
};
class A : public IObject
{
public:
IObject* Create()
{
return new A;
}
void Main()
{
printf("A");
}
};
class B : public IObject
{
public:
IObject* Create()
{
return new B;
}
void Main()
{
printf("B");
}
};
size_t objCount = 0;
IObject* objList[0x10];
void AddObject(IObject* o)
{
objList[objCount++] = o;
}
void RemoveAllObjects()
{
while(objCount)
delete objList[--objCount];
}
IObject* CreateObject(int index)
{
return objList[index]->Create();
}
void Main()
{
IObject* a = CreateObject(0);
IObject* b = CreateObject(1);
a->Main();
b->Main();
delete a;
delete b;
}
int main()
{
AddObject(new A);
AddObject(new B);
Main();
RemoveAllObjects();
}
AddObject add the object description and associate it with an index, CreateObject should create it. It works, but the problem is that with AddObject I'm creating two objects that they will be never used. I'd like to to something like AddObject(A), AddObject(B) without to create them, next create for the first time for example the object B calling CreateObject(1), without to have a startup object where to take informations about how to use the memory. I want it totally dynamic, I won't use a switch(index) { case 0: return new A; etc.
So, it's possible to create something like a Class list instead of an object list?