< previous page page_201 next page >

Page 201
10905-0201a.gif
FIGURE 13.1
Using the default copy constructor.
10905-0201b.gif
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

d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
 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;
d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
continues

 
< previous page page_201 next page >

If you like this book, buy it!