C++ FAQ Celebrating Twenty-One Years of the C++ FAQ!!!
(Click here for a personal note from Marshall Cline.)
Section 36:
[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 std::istream).
  • 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 text or binary format.
  • 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.