title: How do you 'de-serialize' a derived class from serialized data?
body: <p>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?</p>
  
  <p>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.</p>
  
  <p>This way it can be zapped across a socket, a named pipe, etc. to a remote process.</p>
  
  <p>The problem I have is, how do we create an appropriate object from the serialized data?</p>
  
  <p>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.</p>
  
  <p>For example:</p>
  
  <pre><code>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)
  }
  </code></pre>
  
  <p>So after learning the derived object type we invoke the appropriate derived type constructor.</p>
  
  <p>However, this feels awkward and cumbersome. I'm hoping there is a more eloquent way of doing this. Is there?</p>