10.2 Serialization

Serialization is the process of writing or reading an object to or from a persistent storage medium, such as a disk file. The Microsoft Foundation Class Library provides built-in support for serialization in the class CObject. Thus, all classes that are derived from CObject can take advantage of CObject's serialization protocol.

The basic idea of serialization is that an object should be able to write its current state, usually indicated by the value of its member variables, to persistent storage. Later, the object can be re-created by reading, or deserializing, the object's state from the storage. A key point here is that the object itself is responsible for reading and writing its own state. Thus, for a class to be serializable, it must implement the basic serialization operations. As you will see in the following sections, this functionality is easy to add to a class.

The Microsoft Foundation Class Library uses the CArchive class to perform serialization. The object performs serialization operations on the CArchive object without regard to the exact nature of the storage medium. A CArchive object is typically associated with a CFile object, which is normally a disk file.

A CArchive object resembles an I/O stream in that it uses overloaded insertion (<<) and extraction (>>) operators to perform writing and reading operations. But the resemblance to I/O streams is merely cosmetic. Do not confuse the CArchive class with general-purpose I/O streams. I/O streams are for formatted text and the CArchive class is for binary format serialized objects.

There are two main topics regarding serialization in the Microsoft Foundation Class Library that are covered in the following sections.

1.How to make a serializable class

2.How to serialize an object to and from a file object