Sams Teach Yourself C++ in 21 Days

(singke) #1
After a while,catTwois assigned the values in catOne. Two issues are raised here: What
happens if itsAgeis a pointer, and what happens to the original values in catTwo?
Handling member variables that store their values on the free store was discussed earlier
during the examination of the copy constructor. The same issues arise here, as you saw
illustrated in Figures 10.1 and 10.2.
C++ programmers differentiate between a shallow, or member-wise, copy on the one
hand and a deep copy on the other. 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 nec-
essary memory. This was illustrated in Figure 10.3.
An added wrinkle occurs with the assignment operator, however. The object catTwo
already exists and has memory already allocated. That memory must be deleted to avoid
any memory leaks. But what happens if you assign catTwoto itself?
catTwo = catTwo;
No one is likely to do this on purpose. It is, however, possible for this to happen by acci-
dent when references and dereferenced pointers hide the fact that the assignment is to
itself.
If you did not handle this problem carefully,catTwowould delete its memory allocation.
Then, when it was ready to copy in the values from memory on the right-hand side of the
assignment, there would be a very big problem: The value 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 value of the
thispointer. Listing 10.15 shows a class with an assignment operator overloaded. It also
avoids the issue just mentioned.

LISTING10.15 An Assignment Operator
1: // Listing 10.15 - Copy constructors
2:
3: #include <iostream>
4:
5: using namespace std;
6:
7: class Cat
8: {
9: public:
10: Cat(); // default constructor
11: // copy constructor and destructor elided!
12: int GetAge() const { return *itsAge; }
13: int GetWeight() const { return *itsWeight; }

318 Day 10

Free download pdf