Working with Advanced Functions 29910
FIGURE10.1
Using the default copy
constructor.
5itsAgeold CATitsAgeNew CATFree StoreFIGURE10.2
Creating a stray
pointer.^5
itsAgeold CATitsAgeNew CATFree StoreThe solution to this is to create your own copy constructor and to allocate the memory as
required. After the memory is allocated, the old values can be copied into the new mem-
ory. This is called a deep copy. Listing 10.5 illustrates how to do this.LISTING10.5 Copy Constructors
1: // Listing 10.5 - Copy constructors
2:
3: #include <iostream>
4: using namespace std;
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;
19: };
20: