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:
virtual int compareTo(const RWCollectable*) const;
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():
int Bus::compareTo(const RWCollectable* c) const
{ const Bus* b = (const Bus*)c;
if (busNumber_ == b->busNumber_) return 0;
return busNumber_ > b->busNumber_ ? 1 : -1;
}
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.
Don't Use Sorted RWCollections to Store Heterogeneous RWCollectable Objects 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.