Polymorphism + Files

What is the best / most efficient way to load polymorphic data from a file?
I thought you could have an enumeration and for each item to load from a file you could have an integer at the start specifying the type of data, but I think there must be a better way I'm just not sure what.
Example of what I mean:
1
2
3
4
5
6
7
//The syntax isn't really that important for explanation
class base;
class a: base, b: base;
enum polymorphicType {
A,
B
};

and in the loading code you would have (this is the bit I think could be improved):
1
2
3
4
5
6
7
polymorphicType t;
File >> t;
if(t == A) {
newObject = new A;
} else if(t == B) {
newObject = new B;
}


I think there is probably a more efficient/better way of doing this I am just unaware of it. Any help appreciated!
Nope. No better way. All forms of deserialization of polymorphic types are more or less sophisticated variations of what you're proposing. Sooner or later you need a giant if somewhere.
Another example (should be easier to support in the future): http://ideone.com/9NBQln

Not perfect: function which does actual delegation of the build should be non-templated (avoiding multiple copies of the map), error handling would be nice, and code generally should be cleaner.


However, you might want to stich with bunch of ifs or a switch. It is relatively easy to switch to this approach when you loading function will start giving you troubles
Check out the Boost C++ libraries. It supports serialization and deserialization of objects that you write to binary files. In other words, not only the values of the objects, but the info on the TYPE of the object and the TYPES of the data members get saved as well.

I've never used Boost C++ before, but I'm going to! :) Hope this helps.
Okay thank you all for your help!
Last edited on
Topic archived. No new replies allowed.