[36.7] How do I serialize objects that aren't part of an inheritance hierarchy and that don't contain pointers to other objects?
This is the least sophisticated problem, and not surprisingly, it is also the
least sophisticated solution:
- Every class should handle its own serialization and unserialization. You
will typically create a member function that serializes the object to some
sink (such as a std::ostream), and another that allocates a
new object, or perhaps changes an existing object, setting the member
data based on what it reads from some source (such as a
- If your object physically contains another object, e.g., a Car
object might have a member variable of type Engine, the outer object's
serialize() member function should simply call the appropriate
function associated with the member object.
- Use the primitives described earlier to read/write the simple types in
- If a class's data structure might change someday, the class should write
out a version number at the beginning of the object's serialized output. The
version number simply represents the serialized format; it should
not get incremented simply when the class's behavior changes. This
means the version numbers don't need to be fancy — they usually don't need a
major and minor number.