Note that when a constructor has a single argument, you can use the following form when initializing a class object:
// a syntax for initializing a class object when
// using a constructor with one argument
Stonewt incognito = 275;
This is equivalent to the other two forms shown earlier:
// standard syntax forms for initializing class objects
Stonewt incognito(275);
Stonewt incognito = Stonewt(275);
However, the last two forms can also be used with constructors that have multiple arguments.
Next, note the following two assignments from Listing 11.18:
incognito = 276.8;
taft = 325;
The first of these assignments uses the constructor with a type double
argument to convert 276.8
to a type Stonewt
value. This sets the pounds
member of incognito
to 276.8
. Because it uses the constructor, this assignment also sets the stone
and pds_left
members of the class. Similarly, the second assignment converts a type int
value to type double
and then uses Stonewt(double)
to set all three member values in the process.
Finally, note the following function call:
display(422, 2); // convert 422 to double, then to Stonewt
The prototype for display()
indicates that its first argument should be the Stonewt
object. (Either a Stonewt
or a Stonewt &
formal parameter matches a Stonewt
argument.) Confronted with an int
argument, the compiler looks for a Stonewt(int)
constructor to convert the int
to the desired Stonewt
type. Failing to find that constructor, the compiler looks for a constructor with some other built-in type to which an int
can be converted. The Stonewt(double)
constructor fits the bill. So the compiler converts int
to double
and then uses Stonewt(double)
to convert the result to a Stonewt
object.
18.116.12.11