HP Integrity NonStop J-Series User Manual
Page 221

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
[25]
. 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.
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.
Virtual Function isEqual()
The virtual function isEqual() plays a similar role to the tester function of the generic collection
classes described in
RWBoolean isEqual(const RWCollectable* c) const;
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: