Rogue Wave banner
Previous fileTop of DocumentContentsIndex pageNext file
Essential Tools Module User's Guide

6.17 Creating an RWCollectable Object

Here is an outline of how to make your object inherit from RWCollectable. Additional information about how to do each step appears in the indicated section.

  1. Define a default constructor. See Section 6.17.1.

  2. Add the macro RWDECLARE_COLLECTABLE to your class declaration. See Section 6.17.2.

  3. Provide a class identifier for your class by adding one of two definition macros, RWDEFINE_COLLECTABLE or RWDEFINE_NAMED_COLLECTABLE, to one and only one source file (.cpp), to be compiled. See Section 6.17.3.

  4. Add definitions for inherited virtual functions as necessary. You may be able to use inherited definitions. Section 6.17.4 discusses the following virtual functions:

  5. Consider whether you need to define a destructor. See Section 6.17.5.

  6. Add persistence to the class. You may be able to use inherited definitions, or you may have to add definitions for the following functions. See Section 6.17.6.

A note on RWFactory follows these steps. See Section 6.17.7.

6.17.1 Define a Default Constructor

All RWCollectable classes must have a default constructor. The default constructor takes no arguments. The persistence mechanism uses this constructor to create an empty object, then restore that object with appropriate contents.

Default constructors are necessary in order to create vectors of objects in C++, so providing a default constructor is a good habit to get into anyway. Here's a possible definition of a default constructor for our Bus class.

6.17.2 Add RWDECLARE_COLLECTABLE() to your Class Declaration

The example in Section 6.16.3 includes the macro invocation RWDECLARE_COLLECTABLE(Bus) in the declaration for Bus. You must put this macro in your class declaration, using the class name as the argument. Using the macro guarantees that all necessary member functions are declared correctly.

6.17.3 Provide a Class Identifier for Your Class

Polymorphic persistence lets you save a class in one executable, and restore it in a different executable or in a different run of the original executable. The restoring executable can use the class, without prior knowledge of its type. In order to provide polymorphic persistence, a class must have a unique, unchanging identifier. Because classes derived from RWCollectable are polymorphically persistent, they must have such an identifier.

Identifiers can be either numbers or strings. A numeric identifier is an unsigned short with a typedef of RWClassID. A string identifier has a typedef of RWStringID. If you choose to specify a numeric identifier, your class will have an automatically generated string identifier, which will be the same sequence of characters as the name of the class. Similarly, if you choose to specify a string identifier, your class will have an automatically generated numeric ID when used in an executable.

The Essential Tools Module includes two definition macros to provide an identifier for the class you design. If you want to specify a numeric ID, use:

If you want to specify a string ID, use:

Note that you do not include the definition macros in the header file for the class. Rather, the macros are part of a .cpp file that uses the class. You must include exactly one define macro for each RWCollectable class that you're creating, in one and only source file (.cpp). Use the class name as the first argument, and a numeric class ID or string class ID as the second argument. For the bus example, you can include the following definition macros:

or:

The first use provides a numeric ID 200 for class Bus, and the second provides a string ID, "a client", for class Client.

In the remainder of this manual, we use RWDEFINITION_MACRO to indicate that you can choose either of these macros. In example code, we will pick one or the other macro.

Either macro will automatically supply the definitions for the virtual functions isA() and newSpecies(). In Section 6.17.3.1 through Section 6.17.7, we describe these virtual functions, discuss the stringID() method and provide a brief introduction to the RWFactory class, which helps implement polymorphic persistence.

The RWDEFINITION_MACROs do more than merely implement the two mentioned methods. Before you choose not to use one of the provided macros, review them in detail to be sure you understand all that they do.

6.17.3.1 Virtual Function isA()

The virtual function isA() returns a class identifier: a unique number that identifies an object's class. It can be used to determine the class to which an object belongs. Here's the function declaration provided by macro RWDECLARE_COLLECTABLE:

RWClassID is actually a typedef to an unsigned short. Numbers from 0x8000 (hex) and up are reserved for use by Rogue Wave. You may choose a numeric class ID from 0x0001 to 0x7fff. There is a set of class symbols defined in <rw/tooldefs.h> for the Essential Tools Module. Generally, these follow the pattern of a double underscore followed by the class name with all letters in upper case. For example:

The macro RWDECLARE_COLLECTABLE(className) will automatically provide a declaration for isA(). Either RWDEFINITION_MACRO will supply the definition.

6.17.3.2 Virtual Function newSpecies()

The job of this function is to return a pointer to a brand new object of the same type as self. Here is the function declaration provided by macro RWDECLARE_COLLECTABLE:

The definition is automatically provided by either version of RWDEFINITION_MACRO.

6.17.3.3 Function stringID()

The stringID() function acts like a virtual function, but it is not. It returns an instance of RWStringID, a unique string that identifies an object's class. RWStringID is derived from class RWCString. By default, the string identifier for a class is the same as the name of the class. RWStringID can be used instead of, or as a supplement to, RWClassIDs.

6.17.4 Add Definitions for Virtual Functions

Class RWCollectable declares the following virtual functions:

In these functions RWBoolean is a typedef to the bool primitive type where supported, and to an int where support is unavailable. Any class that derives from class RWCollectable should be able to understand any of these methods. Although default definitions are given for all of them in the base class RWCollectable, it is best for you as the class designer to provide definitions tailored to the class at hand.

We've split our discussion of these virtual functions. We discuss the destructor in Section 6.17.5, and the binaryStoreSize(), saveGuts(), and restoreGuts() functions in Section 6.17.6, where we describe how to add persistence to a class. Virtual functions isA() and newSpecies() are declared and defined by macros, so they were discussed above, in Section 6.17.3.1 and Section 6.17.3.2. This section presents discussion on the remaining functions: compareTo(), isEqual(), and hash(). A very brief example, showing how all three functions deal with the same data, appears in Section 6.17.4.4.

6.17.4.1 Virtual Function compareTo()

The virtual function compareTo() is used to order objects relative to each other. This function is required in collection classes that depend on such ordering, such as RWBinaryTree or RWBTree. Here is its declaration:

The function int compareTo(const RWCollectable*) const should return a number greater than zero if self is greater than the argument, a number less than zero if self is less than the argument, and zero if self is equal to the argument.

The definition and meaning of whether one object is greater than, less than, or equal to another object is left to the class designer. The default definition, found in class RWCollectable, is to compare the two addresses of the objects. This default definition should be considered a placeholder; in practice, it is not very useful and could vary from run to run of a program.

Here is a possible definition of compareTo():

Here we are using the bus number as a measure of the ordering of buses. If we need to insert a group of buses into an RWBinaryTree, they would be sorted by their bus number. Note that there are many other possible choices -- we could have used the driver name, in which case they would have been sorted by the driver name. Which choice you use will depend on your particular problem.

There is a hazard here. We have been glib in assuming that the actual type of the RWCollectable which c points to is always a Bus. If a careless user inserted, say, an RWCollectableString into the collection, then the results of the cast (const Bus*)c would be invalid, and dereferencing it could bring disaster. Section 9.7.3 describes this problem. The necessity for all overloaded virtual functions to share the same signatures requires that they return the lowest common denominator, in this case, class RWCollectable. The result is that much compile-time type checking breaks down.


NOTE -- You must be careful that the members of a collection are either homogeneous (i.e., all of the same type), or that there is some way of telling them apart. The member functions isA() or stringID() can be used for this.

6.17.4.2 Virtual Function isEqual()

The virtual function isEqual() plays a similar role to the tester function of the generic collection classes described in Section 7.5.1.

The function RWBoolean isEqual(const RWCollectable*) should return TRUE if the object and its argument are considered equal, and FALSE otherwise. The definition of equality is left to the class designer. The default definition, as defined in class RWCollectable, is to test the two addresses for equality, that is, to test for identity.

Note that isEqual() does not have to be defined as being identical. Rather isEqual can mean that two objects are equivalent in some sense. In fact, the two objects need not even be of the same type. The only requirement is that the object passed as an argument must inherit type RWCollectable. You are responsible for making sure that any typecasts you do are appropriate.

Also note that there is no formal requirement that two objects that compare equal (i.e., compareTo() returns zero) must also return TRUE from isEqual(), although it is hard to imagine a situation where this wouldn't be the case. It is also possible to design a class for which the isEqual test returns true for objects that have different hash values. This would make it impossible to search for such objects in a hash-based collection.

For the Bus class, an appropriate definition of isEqual might be:

Here we are considering buses to be equal if their bus numbers are the same. Again, other choices are possible.

6.17.4.3 Virtual Function hash()

The function hash() should return an appropriate hashing value for the object. Here is the function's declaration:

A possible definition of hash() for our class Bus might be:

The example above simply returns the bus number as a hash value. Alternatively, we could choose the driver's name as a hash value:

In the above example, driver_ is an RWCString that already has a hash function defined.


NOTE -- We expect that two objects that test TRUE for isEqual will hash to the same value.

6.17.4.4 An Example of compareTo(), isEqual(), and hash()

We have described three inherited virtual functions: compareTo(), isEqual(), and hash(). Here is an example that defines a set of objects, and applies the functions. The results of the functions appear as comments in the code.

Note that the compareTo() function for RWCollectableStrings has been defined to compare strings lexicographically in a case sensitive manner. See class RWCString in the Essential Tools Module Reference Guide for details.

6.17.5 Object Destruction

All objects inheriting from class RWCollectable inherit a virtual destructor. Hence, the actual type of the object need not be known until run time in order to delete the object. This allows all items in a collection to be deleted without knowing their actual type.

As with any C++ class, objects inheriting from RWCollectable may need a destructor to release the resources they hold. In the case of Bus, the names of passengers and customers are RWCollectableStrings that were allocated off the heap. Hence, they must be reclaimed. Because these strings never appear outside the scope of the class, we do not have to worry about the user having access to them. Hence, we can confidently delete them in the destructor, knowing that no dangling pointers will be left.

Furthermore, because the set pointed to by customers_ is a superset of the set pointed to by passengers_, it is essential that we delete only the contents of customers_.

Here is a possible definition:

Note that the language guarantees that it is okay to call delete on the pointer passengers_ even if it is nil. See Section 18.4.1.1.13p1 of the C++ Standard.

6.17.6 How to Add Polymorphic Persistence

The saveGuts() and restoreGuts() virtual functions are responsible for saving and restoring the internal state of RWCollectable objects. To add persistence to your RWCollectable class, you must override the saveGuts() and restoreGuts() virtual member functions so that they write out all of your object's member data. Section 6.17.6.1 and Section 6.17.6.2 describe approaches you can use to correctly define these functions. Section 6.17.6.3 describes how these functions handle multiply-referenced objects.

Polymorphically saving an object to a file may require some knowledge of the number of bytes that need to be allocated for storage of an object. The binaryStoreSize() function calculates this value. Section 6.17.6.4 describes how to use binaryStoreSize().

RWCollection has its own versions of the saveGuts() and restoreGuts() functions that are used to polymorphically save collections that inherit from that class. Section 6.17.6.5 briefly describes how these functions work.

6.17.6.1 Virtual Functions saveGuts(RWFile&) and saveGuts(RWvostream&)

The saveGuts(RWFile&) and saveGuts(RWvostream&) virtual functions are responsible for polymorphically saving the internal state of an RWCollectable object on either a binary file, using class RWFile, or on a virtual output stream, using class RWvostream. For a description of the persistence mechanism, see Chapter 9. This allows the object to be restored at some later time, or in a different location. Here are some rules for defining a saveGuts() function:

  1. Save the state of your base class by calling its version of saveGuts().

  2. For each type of member data, save its state. How to do this depends upon the type of the member data:

With these rules in mind, let's look at a possible definition of the saveGuts() functions for the Bus example:

Member data busNumber_ is an int, a C++ primitive. It is stored directly using either RWFile::Write(int), or RWvostream::operator<<(int).

Member data driver_ is an RWCString. It does not inherit from RWCollectable. It is stored using:

Member data customers_ is an RWSet. It does inherit from RWCollectable. It is stored using:

Finally, member data passengers_ is a little tricky. This data is a pointer to an RWSet, which inherits from RWCollectable. However, there is the possibility that the pointer is nil. If it is nil, then passing it to:

would be disastrous, as we would have to dereference passengers_:

Instead, since our class has declared passengers_ as an RWSet*, we pass it to:

which automatically detects the nil pointer and stores a record of it.

6.17.6.2 Virtual Functions restoreGuts(RWFile&) and restoreGuts(RWvistream&)

In a manner similar to saveGuts(), these virtual functions are used to restore the internal state of an RWCollectable from a file or stream. Here is a definition of these functions for the Bus class:

Note that the pointer passengers_ is restored using:

If the original passengers_ is non-nil, then this function restores a new RWSet off the heap and returns a pointer to it. Otherwise, it returns a nil pointer. Either way, the old contents of passengers_ are replaced. Hence, we must call delete passengers_ first.

6.17.6.3 Multiply-referenced Objects

A passenger name can exist in the set pointed to by customers_ and in the set pointed to by passengers_; that is, both collections might contain the same string. When the Bus is restored, we want to make sure that the pointer relationship is maintained, and that our restoration does not create another copy of the string.

We do not have to do anything special to insure that the pointer relationship stays as it should be. Consider the call:

Because passenger_ is a subset of customer_, the function addPassenger puts the name on both the customer list and the passenger list. When we save aBus to aFile, both lists are saved in a single call: first the customer list, then the passenger list. The polymorphic persistence machinery saves the first reference to John, but for the second reference it merely stores a reference to the first copy. During the restore, both references will resolve to the same object, replicating the original morphology of the collection.

6.17.6.4 Virtual Function binaryStoreSize()

The binaryStoreSize() virtual function calculates the number of bytes necessary to store an object using RWFile. The function is:

This function is useful for classes RWFileManager and RWBTreeOnDisk, which require allocation of space for an object before it can be stored. The non-virtual function recursiveStoreSize() returns the number of bytes that is actually stored. Recursive store size uses binaryStoreSize() to do its work.

Writing a version of binaryStoreSize() is usually straightforward. You just follow the pattern set by saveGuts(RWFile&), except that instead of saving member data, you add up their sizes. The only real difference is a syntactic one: instead of insertion operators, you use sizeof() and the member functions indicated below:

Here is a sample definition of a binaryStoreSize() function for class Bus:

6.17.6.5 Polymorphically Persisting Custom Collections

The versions of saveGuts() and restoreGuts() that the Essential Tools Module built into class RWCollection are sufficient for most collection classes. The function RWCollection::saveGuts() works by repeatedly calling:

for each item in the collection. Similarly, RWCollection::restoreGuts() works by repeatedly calling:

This operator allocates a new object of the proper type off the heap, then calls insert(). Because all of the Rogue Wave Smalltalk-like collection classes inherit from RWCollection, they all use this mechanism.

If you decide to write your own collection classes that inherit from class RWCollection, you will rarely have to define your own saveGuts() or restoreGuts().

There are exceptions. For example, class RWBinaryTree has its own version of saveGuts(). This is necessary because the default version of saveGuts() stores items in order. For a binary tree, this would result in a severely unbalanced tree when the tree was read back in -- essentially, the degenerate case of a linked list. Hence, RWBinaryTree's version of saveGuts() stores the tree level-by-level.

When you design your class, you must determine whether it has similar special requirements which may need a custom version of saveGuts() and restoreGuts().

6.17.7 A Note on the RWFactory

The RWDEFINITION_MACROs can appear as the following:

or, using a string ID:

In the .cpp file for the bus example, the macros appear like this:

and:

Because you use these macros, a program can allow a new instance of your class to be created given only its RWClassID:

or its RWStringID:

The pointer theFactory is a global pointer that points to a one-of-a-kind global instance of class RWFactory, used to hold information about all RWCollectable classes that have instances in the executable. The create() method of RWFactory is used internally by the polymorphic persistence machinery to create a new instance of a persisted object whose type is not known at run time. You will not normally use this capability in your own source code, because the use of RWFactory is generally transparent to the user. See the Essential Tools Module Reference Guide for more details on RWFactory.



Previous fileTop of DocumentContentsIndex pageNext file

©2004 Copyright Quovadx, Inc. All Rights Reserved.
Rogue Wave and SourcePro are registered trademarks of Quovadx, Inc. in the United States and other countries. All other trademarks are the property of their respective owners.
Contact Rogue Wave about documentation or support issues.