donderdag 5 juli 2007

impicit type cast to class object

In C++, any constructor that takes a single argument acts as a blueprint for converting a value of that argument type to the class type. Thus the constructor

Stonewt(double lbs); // template for double-to-Stonewt conversion

serves as instructions for converting a type double value to a type Stonewt value, That is, you can write code like the following:

Stonewt myCat; // create a Stonewt object
myCat = 19.6; // use Stonewt(double) to convert 19.6 to Stonewt

The program uses the Stonewt(double) constructor to construct a temporary Stonewt object, using 19.6 as the initialization value. Then memberwise assignment copies the contents of the temporary object into myCat. This process is termed an implicit conversion because it happens automatically, without the need of an explicit cast.

Only a constructor that can be used with just one argument works as a conversion function. The constructor

Stonewt(int stn, double lbs);

has two arguments, so it cannot be used to convert types.

REMEMBER
A c++ constructor that contains one argument defines a type conversion from the argument type to the class type. If the constructor is qualified with the keyword explicit, the constructor is used for explicit conversions only; otherwise it is also used for implicit conversions.

1 opmerking:

Anoniem zei

Hello. This post is likeable, and your blog is very interesting, congratulations :-). I will add in my blogroll =). If possible gives a last there on my blog, it is about the MP3 e MP4, I hope you enjoy. The address is http://mp3-mp4-brasil.blogspot.com. A hug.