Sign in to follow this  
Samurai Jack

Automated file loader (Not quite class factory)

Recommended Posts

Samurai Jack    455
Greetings! I have a C++ problem regarding a file loader. I would like to have somekind of automated loader. Let us say, we have a few classes:
class Person (which can load/save name, surname, age)
class Company (which can load/save factory details)
class Date (which can load/save date & time)
What I could do is some kind of enumerators and a class factory
char code = getchar(fs);
switch (code)
case 1: { Person* p = new Person(); p.Load(fs); };
case 2: { Company* c = new Company(); c.Load(fs); };
case 3: { Date* d = new Date(); d.Load(fs); };
I do not like this too much because allways when you add a new object like:
class Airplane() (which can laod/save passanger data, fuel etc..)
You allways have to update the class factory. It would be great if Airplane could inherit from a base class and as soon it is inherited it has all the capabilities to load and save. So when you define a class like Airplane it can in theory be loaded. Or do I have to do something like a header ".h" file, which contains all classes? Like:
BaseClass* array[] = { new Person, new Company, new Date };
and then allways when a code is read out of a file, I would iterate the array like this:
for each object in array do if array[current].CodeValid(code_from_file) then base* pObject = array[current].CreateNew();
Does someone have an idea or suggestion?

Share this post

Link to post
Share on other sites
Giallanon    1893
You could use factory.
Store the class name in the file instead of a code and then, use factory to spawn the right class.

char *className = readStringFromFile (fs);
BaseClass *c = Factory::SpawnClass (className);
c->Load (fs);

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this