|
|
|
|
|
|
|
FIGURE 13.1
Using the default copy constructor. |
|
|
|
|
|
|
|
|
FIGURE 13.2
Creating a stray pointer. |
|
|
|
|
|
|
|
|
The solution to this is to define your own copy constructor and to allocate memory as required in the copy. Once the memory is allocated, the old values can be copied into the new memory. This is called a deep copy. Listing 13.3 illustrates how to do this. |
|
|
|
|
|
|
|
|
LISTING 13.3 COPY CONSTRUCTORS |
|
|
|
 |
|
|
|
|
1: // Listing 13.3
2: // Copy constructors
3:
4: #include <iostream.h>
5:
6: class CAT
7: {
8: public:
9: CAT(); // default constructor
10: CAT (const CAT &); // copy constructor
11: ~CAT(); // destructor
12: int GetAge() const { return *itsAge; }
13: int GetWeight() const { return *itsWeight; }
14: void SetAge (int age) { *itsAge = age; }
15:
16: private:
17: int *itsAge;
18: int *itsWeight; |
|
|
|
 |
|
|
|
|
continues |
|
|
|
|
|