< previous page page_216 next page >

Page 216
operator=.
Remember that the compiler provides a default constructor, destructor, and copy constructor. The fourth and final function that is supplied by the compiler, if you don't specify one, is the assignment operator (operator=()).
This operator is called whenever you assign to an object. For example:
CAT catOne(5,7);
CAT catTwo(3,4);
//  other code here
catTwo = catOne;
Here, catOne is created and initialized with itsAge equal to 5 and itsWeight equal to 7. catTwo is then created and assigned the values 3 and 4.
Note, in this case the copy constructor is not called. catTwo already exists; there is no need to construct it.
In Hour 13, Advanced Functions, I discussed the difference between a shallow or member-wise copy and a deep copy. A shallow copy just copies the members, and both objects end up pointing to the same area on the free store. A deep copy allocates the necessary memory. You saw an illustration of that in Figure 13.1; refer back to that figure if you need to refresh your memory.
You see the same issue here with assignment as you did with the copy constructor. There is an added wrinkle with the assignment operator, however. The object catTwo already exists and already has memory allocated. That memory must be deleted if there is to be no memory leak.
So the first thing you must do when implementing the assignment operator is delete the memory assigned to its pointers. But what happens if you assign catTwo to itself, like this:
catTwo = catTwo;
No one is likely to do this on purpose, but the program must be able to handle it. More important, it is possible for this to happen by accident when references and dereferenced pointers hide the fact that the object's assignment is to itself.
If you did not handle this problem carefully, catTwo would delete its memory allocation. Then, when it was ready to copy in the memory from the right-hand side of the assignment, it would have a very big problem: the memory would be gone.
To protect against this, your assignment operator must check to see if the right-hand side of the assignment operator is the object itself. It does this by examining the this pointer. Listing 14.6 shows a class with an assignment operator.

 
< previous page page_216 next page >

If you like this book, buy it!