Share via


Serialization (Object Persistence)

OverviewHow Do I

This article explains the serialization mechanism provided in the Microsoft Foundation Class Library (MFC) to allow objects to persist between runs of your program.

“Serialization” is the process of writing or reading an object to or from a persistent storage medium, such as a disk file. MFC supplies built-in support for serialization in the class CObject. Thus, all classes 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. Serialization handles all the details of object pointers and circular references to objects that are used when you serialize an object. A key point 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 shown in the Serialization group of articles, it is easy to add this functionality to a class.

MFC uses an object of the CArchive class as an intermediary between the object to be serialized and the storage medium. This object is always associated with a CFile object, from which it obtains the necessary information for serialization, including the file name and whether the requested operation is a read or write. The object that performs a serialization operation can use the CArchive object without regard to the nature of the storage medium.

A CArchive object uses overloaded insertion (<<) and extraction (>>) operators to perform writing and reading operations. For more information, see Storing and Loading CObjects via an Archive in the article Serialization: Serializing an Object.

Note   Do not confuse the CArchive class with general-purpose iostream classes, which are for formatted text only. The CArchive class is for binary-format serialized objects.

The following articles cover the two main tasks required for serialization:

The article Serialization: Serialization vs. Database Input/Output is part of the group of articles on database topics. The article describes when serialization is an appropriate input/output technique in database applications.