When equality does not apply

For some classes, equality doesn't make sense and you shouldn't include an equality operator. Perhaps the clearest example is in Taligent's Properties, where there are classes that are named envelopes for other classes that are represented as void*'s. In this case, the envelope can't determine equality among its fields and cannot meaningfully determine when it is equal to another. Other Taligent examples are TView, TStream, TMonitor, and TThreadProgram.

NOTE Taligent's MCollectible might force you to supply equality; make it very clear with comments and documentation that this is temporary.

One good test is that where assignment doesn't make sense, equality doesn't either. If you cannot define operator=, you shouldn't define operator==.

Equality sample

If different subclasses are always unequal, your equality operator should follow this general form. You can skip step 2 in the following code if your superclass already checks it. If you do have cases where objects of different classes should compare equal, then you have a bit more work to do:

      // TB inherits from TA
      Boolean TB::operator == (const TB& other) const {
          Boolean result;
          // Step 1. fast address check, useful if it occurs often
          if (this == &other) result = TRUE;
          // Step 2. must be same class
          else if (typeid(*this) != typeid(other)) result = FALSE;
          // Step 3. check superclasses ==
          else if (TA::operator!=(other)) result = FALSE;
          // Step 4. fields
          else if (fField1 == other.fField1 && fFieldN == other.fFieldN) result = TRUE;
          return result;
It is usually more efficient to define operator== as a global function. Do this for the highest class in your hierarchy, where that class' definition should include steps 1 and 2 of the example, and a call to a protected member function PrivateEquality(const TMyClass&). Any subclass then needs to override PrivateEquality to do steps 3 and 4. This makes sure that if X== Y, then Y==X, and avoids making multiple checks in steps 1 and 2.

[Contents] [Previous] [Next]
Click the icon to mail questions or corrections about this material to Taligent personnel.
Copyright©1995 Taligent,Inc. All rights reserved.

Generated with WebMaker