Streaming the Serialized Object
Now an instance of class real_property can be written to a file and read back.
 
// real_estate.cpp
 
real_property real1
("1980 Main St. Corvallis, Oregon","50x100"); // 1
real_property real2;
{ // 2
 
ofstream fout("real_estate.dat"); // 3
 
RWpostream postr(fout);
RWObjectOutputStream out = RWCompactObjectOutputStreamImp::
make(RWDataToVirtualOutputStreamImp::
make(postr)); // 4
out << real1; // 5
}
 
ifstream fin("real_estate.dat"); // 6
RWpistream pistr(fin);
RWObjectInputStream in = RWCompactObjectInputStreamImp::
make(RWDataFromVirtualInputStreamImp::
make(pistr)); // 7
in >> real2; // 8
//1 Create a real_property object.
//2 Create a local scope so the output file closes automatically when it’s no longer needed.
//3 Open a file for output.
//4 Create a data stream using the standard file stream just opened and then create a compact object output stream from the data stream.
//5 Stream out the contents of real1 to the file in compact format.
//6 Now open the file for input.
//7 Create a data stream and then create a compact object input stream from the data stream.
//8 Read the data from the first variable (real1) into the second (real2).
A more complete version of this example with more explanation is presented in Saving and Restoring an Object by Value. If you wish to stream objects as pointers, see Saving and Restoring an Object by Pointer.