I have some polymorphic classes and can *almost* gracefully serialize them with a virtual serialize member function that first calls the base class' serialize member function, then does its own serialization. Unfortunately, this means they have to serialize their type, meaning I have to manage them all and make sure their type ID number is different for each class.
This leads to the main problem: how do I gracefully deserialize the objects? I can't make constructors virtual for obvious reasons, so I have to have a single function to deserialize the data and create the instances with...with if/switch-case statements. This seems to me to be a direct insult to polymorphism, even more so than the classes having to know their type ID number.
Could someone propose an elegant solution to this? I'm running out of ideas. The code works, I just sense the presence of evil whenever I read through it :(
Note: if it helps, I'm serializing to/deserializing from files using std::ofstream and std::ifstream. The polymorphism is recursive (meaning that a grouping of Objs is-a Obj).
You need a creator/factory that knows about the serialized classes. It reads some short token, decides what class needs to be constructed and constructs from the remainder from the stream. How? The serialized class itself can have constructor that takes the input stream as a parameter.