14.3.1. Equality Operators

Image

Ordinarily, classes in C++ define the equality operator to test whether two objects are equivalent. That is, they usually compare every data member and treat two objects as equal if and only if all the corresponding members are equal. In line with this design philosophy, our Sales_data equality operator should compare the bookNo as well as the sales figures:

bool operator==(const Sales_data &lhs, const Sales_data &rhs)
{
    return lhs.isbn() == rhs.isbn() &&
           lhs.units_sold == rhs.units_sold &&
           lhs.revenue == rhs.revenue;
}
bool operator!=(const Sales_data &lhs, const Sales_data &rhs)
{
    return !(lhs == rhs);
}

The definition of these functions is trivial. More important are the design principles that these functions embody:

• If a class has an operation to determine whether two objects are equal, it should define that function as operator== rather than as a named function: Users will expect to be able to compare objects using ==; providing == means they won’t need to learn and remember a new name for the operation; and it is easier to use the library containers and algorithms with classes that define the == operator.

• If a class defines operator==, that operator ordinarily should determine whether the given objects contain equivalent data.

• Ordinarily, the equality operator should be transitive, meaning that if a == b and b == c are both true, then a == c should also be true.

• If a class defines operator==, it should also define operator!=. Users will expect that if they can use == then they can also use !=, and vice versa.

• One of the equality or inequality operators should delegate the work to the other. That is, one of these operators should do the real work to compare objects. The other should call the one that does the real work.


Image Best Practices

Classes for which there is a logical meaning for equality normally should define operator==. Classes that define == make it easier for users to use the class with the library algorithms.



Exercises Section 14.3.1

Exercise 14.16: Define equality and inequality operators for your StrBlob12.1.1, p. 456), StrBlobPtr12.1.6, p. 474), StrVec13.5, p. 526), and String13.5, p. 531) classes.

Exercise 14.17: Should the class you chose for exercise 7.40 from § 7.5.1 (p. 291) define the equality operators? If so, implement them. If not, explain why not.


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.103.204