Sams Teach Yourself C++ in 21 Days

(singke) #1
Working with Advanced Functions 323

10


class Counter
{
Counter (int x);
// ..
};
This constructor creates Counterobjects from integers. It does this by creating a tempo-
rary and unnamed counter. For illustration purposes, suppose that the temporary Counter
object created from the integer is called wasInt.
Step 3: Assign wasIntto theCtr,which is equivalent to
theCtr = wasInt;
In this step,wasInt(the temporary Countercreated when you ran the constructor) is
substituted for what was on the right-hand side of the assignment operator. That is, now
that the compiler has made a temporary Counterfor you, it initializes theCtrwith that
temporary object.
To further understand this, you must understand that alloperator overloading works the
same way—you declare an overloaded operator using the keyword operator. With
binary operators (such as =or +), the right-hand side variable becomes the parameter.
This is done by the constructor. Thus
a = b;
becomes
a.operator=(b);
What happens, however, if you try to reverse the assignment with the following?
1: Counter theCtr(5);
2: int theInt = theCtr;
3: cout << “theInt : “ << theInt << endl;
Again, this generates a compile error. Although the compiler now knows how to create a
Counterout of an int, it does not know how to reverse the process.

Conversion Operators ..........................................................................................


To solve the conversion back to a different type from objects of your class, C++ provides
conversion operators. These conversion operators can be added to your class. This
enables your class to specify how to do implicit conversions to built-in types. Listing
10.18 illustrates this. One note, however: Conversion operators do not specify a return
value, even though they do return a converted value.
Free download pdf