Reputation:
I need to serialize/deserialize a polymorphic hierarchy but I am somewhat unclear on the format.
The way I figure it, each unique object type should serialize itself, beginning with a "magic number" to signify the type that the factory later needs to deserialize. However, should deserialization be handled by the individual classes or explicitly and entirely by the factory?
I guess if deserialization is handled by the individual classes, it will be more "elegant" and structured, but considering that most if not all objects inherit from other objects and that data must be used to initialize the base classes constructors, I am a little unclear how is a member method of the inheriting class will be able to achieve this, since base classes initialization must precede it.
The other way around is to detach the deserialization method from the individual classes and move all that code to a factory, but that will make it much harder to implement deserialization in a fashion full reverse of serialization. This will mean I have to extract all data needed for the full chain of inheritance for each class, put it on the stack and use it to call the appropriate constructors.
Any thoughts on the subject?
Upvotes: 3
Views: 584
Reputation: 14392
Serializing and deserializing should be as symmetrical as possible. It is best done by the class itself with a deserializing function (e.g. operator>>()
), so the factory creates the class based on the ID and then passes the stream to the the deserialization function. That function can then call the deserialization function of the base class.
Upvotes: 1