UMBC CMSC 202 Spring '00 CSEE | 202 | 202 S'00 | lectures | news | help

Why Your Set Probably Needs operator =()

Consider the following code fragment: Set C, A, B; int i; for (i=0; i<5; i++) { A.add(i); B.add(i+2); } This is a fairly simple example of how you might start a test program for proj2. It starts by declaring a few Sets and adding some elements to a few of them.

We want to make things vaguely interesting, so we elect to make the sets a little different to start with. The default constructor should make all three Sets empty at first ({}) but soon A should be {0,1,2,3,4} and B should be {2,3,4,5,6} since B just adds the same number of elements as A, but it adds two to each one before adding it.

At this point, we move onto the next code fragment...

C = A && B; C = A || B; C = A - B; This section produces no output, but should give you a feel for how these operators will be called. FYI, given the sets above the results are: A && B = {2,3,4} A || B = {0,1,2,3,4,5,6} A - B = {0,1} Ok. So far so good. Now we move on to try testing equality for our as-of-yet-successful Set class. Rather than remove elements by hand (how menial), we decide to just make A a copy of B, as below. A = B; Now we go to test equality and make sure that it works. if (A == B) cout << "Equality works."; That fragment will almost undoubtedly print Equality works.

So we decide to make sure both cases for equality testing work (that it returns true when they are equal and false otherwise) so we opt to take 4 out of A and retest. Everybody watching?

A.remove(4); if (A == B) cout << "Uh oh."; Now, at this point you've probably guessed that Uh oh. gets printed to the screen. It almost undoubtedly does. Who knows why?

Take a minute and think about it. No rush. Actually, take the evening. I'll post the answer tomorrow.

Here's a hint: In C++, if you don't provide an assignment operator, the language provides one for you. The default assignment operator works as follows. If we're assigning A = B:

for each field, f, in the object definition A.f = B.f Go to it.


CSEE | 202 | 202 S'00 | lectures | news | help