17.12. Input/Output of Objects
This chapter and Chapter 15 introduced C++'s object-oriented style of input/output. However, our examples concentrated on I/O of traditional data types rather than objects of user-defined types. In Chapter 11, we showed how to input and output objects using operator overloading. We accomplished object input by overloading the stream extraction operator >> for the appropriate istream. We accomplished object output by overloading the stream insertion operator << for the appropriate ostream. In both cases, only an object's data members were input or output, and, in each case, they were in a format meaningful only for objects of that particular abstract data type. An object's member functions are not input and output with the object's data; rather, one copy of the class's member functions remains available internally and is shared by all objects of the class.
When object data members are output to a disk file, we lose the object's type information. We store only data bytes, not type information, on the disk. If the program that reads this data knows the object type to which the data corresponds, the program will read the data into objects of that type.
An interesting problem occurs when we store objects of different types in the same file. How can we distinguish them (or their collections of data members) as we read them into a program? The problem is that objects typically do not have type fields (we studied this issue carefully in Chapter 13).
One approach would be to have each overloaded output operator output a type code preceding each collection of data members that represents one object. Then object input would always begin by reading the type-code field and using a switch statement to invoke the proper overloaded function. Although this solution lacks the elegance of polymorphic programming, it provides a workable mechanism for retaining objects in files and retrieving them as needed.