What I want to do: I load data from a XML file (this goes fine). The XML tells the program to create class instances (from specific different classes, like Car
or Plane
) which then will exist within the program. These class instance objects are subclasses of an overarching Object
base class.
The XML file stores what type of object needs to be created in the form of a number, from which the program will determine which class of object to create.
I could use a switch
statement and enumerate all types of objects, but this is incredibly taxing on performance when adding loads of instances of objects. So instead, I want a mapping from char[2]
to the required class. (Note: to the class type itself, not an instance of the class.)
For example, if the XML attribute says 'type=0x01'
, then an object from the class Car
will be made, while if 'type=0x02
' then a Plane
object will be made. (Both are kinds of Object
)
In this way, I want to use a constant map to get this done. I want to write something like
map<char[2],class> ObjectsList = {
{0x01,Car},
{0x02,Plane}
//etc, etc.
}
...
// while loading data from xml file on which objects need to get created,
// an object-tag gives data from 'type' attribute, and the program stores
// it in 'char[2] type';
char[2] type = getattributestufffromxml("type");
ObjectsList[type] newObject = memoryallocator.allocate(sizeof(ObjectsList[type]);
newObject.Init(); //inherited function from Object
The idea of this is to create a faster approach rather than sticking with a switch-statement, which is awful when creating hundreds of objects.
What do I need to do to get from the above to something that's valid C++? I do not know how I can store class types in a map. (I get compiler errors such as, 'parameter 2/4 are invalid')