< previous page page_218 next page >

Page 218
LISTING 14.6 continued
d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
48:        cout << Setting frisky to 6\n;
49:        frisky.SetAge(6);
50:        CAT whiskers;
51:        cout << whiskers' age:  << whiskers.GetAge() << endl;
52:        cout << copying frisky to whiskers\n;
53:        whiskers = frisky;
54:        cout << whiskers' age:  << whiskers.GetAge() << endl;
55:        return 0;
56:     }

Output:
frisky's age: 5
Setting frisky to 6;
whiskers' age: 5
copying frisky to whiskers
whiskers' age: 6
Listing 14.6 brings back the CAT class, and leaves out the copy constructor and destructor to save room. On line 14, the assignment operator is declared, and on lines 3041, it is defined.
On line 32, the current object (the CAT being assigned to) is tested to see if it is the same as the CAT being assigned. This is done by checking if the address of rhs is the same as the address stored in the this pointer.
Of course, the equality operator (==) can be overloaded as well, enabling you to determine for yourself what it means for your objects to be equal.
On lines 3437 the member variables are deleted and then re-created on the heap. While this is not strictly necessary, it is good, clean programming practice and will save you from memory leaks when working with variable length objects that do not overload their assignment operator.

Conversion Operators
What happens when you try to assign a variable of a built-in type, such as int or unsignedshort, to an object of a user-defined class? Listing 14.11 brings back the Counter class and attempts to assign a variable of type int to a Counter object.

 
< previous page page_218 next page >

If you like this book, buy it!