Example One: Saving Polymorphically
This example constructs an empty collection, inserts objects into that collection, then saves the collection polymorphically to standard output. Notice that example one creates and saves a collection that includes two copies of the same object and two other objects. The four objects have three different types. When example one saves the collection and when example two restores the collection, we see that:
*The morphology of the collection is maintained;
*The process that restores the collection does not know the object's type before it restores that object.
Here is the first example:
 
#include <rw/ordcltn.h>
#include <rw/collstr.h>
#include <rw/collint.h>
#include <rw/tools/ctdatetime.h>
#include <rw/pstream.h>
 
int main()
{
// Construct an empty collection
RWOrdered collection;
 
// Insert objects into the collection.
 
RWCollectableString* george;
george = new RWCollectableString("George");
 
collection.insert(george); // Add a string once
collection.insert(george); // Add a string twice
collection.insert(new RWCollectableInt(100));
collection.insert(new RWCollectableDateTime("May 3, 1959",
RWDateTime::setDate));
 
// "Store" to std::cout using portable stream.
RWpostream ostr(std::cout);
 
// The following statement calls the insertion operator:
// Rwvistream&
// operator<<(RWvistream&, const RWCollectable&);
ostr << collection;
 
// Now delete all the members in collection.
// clearAndDestroy() has been written so that it deletes
// each object only once, so that you do not have to
// worry about deleting the same object too many times.
 
collection.clearAndDestroy();
 
return 0;
}
Note that there are three types of objects stored in collection, an RWCollectableDate, an RWCollectableInt, and two RWCollectableStrings. The same RWCollectableString, george, is inserted into collection twice.