Sams Teach Yourself C++ in 21 Days

(singke) #1
Listing 10.15 brings back the Catclass, but leaves out the copy constructor and
destructor to save room. New to the listing on line 15 is the declaration of the
assignment operator. This is the method that will be used to overload the assignment
operator. On lines 31–38, this overload method is defined.
On line 33, the current object (the Catbeing assigned to) is tested to see whether it is the
same as the Catbeing assigned. This is done by checking whether the address of the Cat
object on the right side (rhs) is the same as the address stored in the thispointer. If they
are the same, there is no need to do anything because the object on the left is the same
object that is on the right. Because of this, line 34 returns the current object.
If the object on the right-hand side is not the same, then the members are copied on lines
35 and 36 before returning.
You see the use of the assignment operator on line 50 of the main program when a Cat
object called Friskyis assigned to the Catobject Whiskers. The rest of this listing
should be familiar.
This listing assumes that if the two objects are pointing to the same address, then they
must be the same. 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.

Handling Data Type Conversion..........................................................................


Now that you’ve seen how to assign an object to another object of the same type, con-
sider another situation. What happens when you try to assign a variable of a built-in type,
such as intor unsigned short, to an object of a user-defined class? For example, the
Counterclass was created earlier. What if you wanted to assign an integer to this class?
Listing 10.16 attempts to do this.

320 Day 10


ANALYSIS

CAUTION Listing 10.16 will not compile!

LISTING10.16 Attempting to Assign a Counter to an int
1: // Listing 10.16 - This code won’t compile!
2:
3: #include <iostream>
4:
5: using namespace std;
6:
7: class Counter
8: {
Free download pdf