< previous page page_217 next page >

Page 217
LISTING 14.6 AN ASSIGNMENT OPERATOR

d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
 1:     // Listing 14.6
 2:     // Copy constructors
 3:
 4:     #include <iostream.h>
 5:
 6:     class CAT
 7:     {
 8:     public:
 9:       CAT();                         // default constructor
10:       // copy constructor and destructor elided!
11:       int GetAge() const { return *itsAge; }
12:       int GetWeight() const { return *itsWeight; }
13:       void SetAge(int age) { *itsAge = age; }
14:       CAT operator=(const CAT &);
15:
16:     private:
17:        int *itsAge;
18:        int *itsWeight;
19:     };
20:
21:     CAT::CAT()
22:     {
23:        itsAge = new int;
24:        itsWeight = new int;
25:        *itsAge = 5;
26:        *itsWeight = 9;
27:     }
28:
29:
30:     CAT CAT::operator=(const CAT & rhs)
31:     {
32:        if (this == &rhs)
33:           return *this;
34:        delete itsAge;
35:        delete itsWeight;
36:        itsAge = new int;
37:        itsWeight = new int;
38:        *itsAge = rhs.GetAge();
39:        *itsWeight = rhs.GetWeight();
40:        return *this;
41:     }
42:
43:
44:     int main()
45:     {
46:        CAT frisky;
47:        cout << frisky's age:  << frisky.GetAge() << endl;
d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
continues

 
< previous page page_217 next page >

If you like this book, buy it!