Hello.
How do you 'de-serialize' a derived class from serialized data? Or maybe I should say, is there a better way to 'de-serialize' data into derived classes?
For example, suppose you had a pure virtual base class (B) that is inherited by three other classes, X, Y and Z. Moreover, we have a method, serialize(), that will translate X:B, Y:B and Z:B into serialized data.
This way it can be zapped across a socket, a named pipe, etc. to a remote process.
The problem I have is, how do we create an appropriate object from the serialized data?
The only solution I can come up with is including an identifier in the serialized data that indicates the final derived object type. Where the receiver, first parses the derived type field from the serialized data, and then uses a switch statement (or some sort of logic like that) to invoke the appropriate constructor.
For example:
B deserialize( serial_data )
{
parse the derived type from the serial_data
switch (derived type)
case X
return X(serial_data)
case Y
return Y(serial_data)
case Z
return Z(serial_data)
}
So after learning the derived object type we invoke the appropriate derived type constructor.
However, this feels awkward and cumbersome. I'm hoping there is a more eloquent way of doing this. Is there?