Type Conversions
A set of well-defined rules are followed
by the compiler when representations in
various types need to be or
should be converted.
If the compiler does not know what to do
with a type mismatch, you get a
compiler error.
Automatic Conversions
double D1 = 6; // becomes 6.0 as a double
int I1 = 12.8; // becomes 12 as an int
// note: truncation
These are both numeric types,
so conversion is well defined.
Does not work:
(you get a compiler error)
int * px = 56;
I was asked in a class earlier this
semester:
Can I force the pointer's value to an int?
Answer: Yes, but you do not want to!
int * px = (int *) 56; // type cast
Conversion of user-defined types
Any constructor taking a single argument
is defined as doing conversion:
from argument type to class type.
class X {
public:
X(int); // conversion constructor
// int -> X
}
Use:
X Y; Y = 300; // implicit conversion
Creates temporary X object, using X(int),
and a default (since I did not show one)
copy assignment operator to put into Y.
more implicit conversion
class X { class Z {
public: public:
X(int); void foo(X);
X bar(int);
} }
One use:
Z1.foo(308)
foo expects an X,
uses X(int) as conversion,
and creates temporary for the actual argument.
Another use:
X bar(int a) {
return 61;
}
implicit conversion of return value
Combine automatic conversion
with implicit conversion!
(Same declarations.)
class X { class Z {
public: public:
X(int); void foo(X);
X bar(int);
} }
Use:
Z1.foo(14.6)
Automatic conversion of 14.6 (double)
to 14 (int).
Then, uses X(int) as conversion,
and creates temporary for the actual argument.
To turn off implicit conversion:
Place keyword explicit
before constructor in declaration only.
class X {
public:
explicit X(int);
}
Several uses:
X Y(16); // OK. . .explicit constructor request X Y; Y = X(16); // OK. . .explicit constructor request X Y; Y = (X) 16; // OK. . .explicit type cast X Y; Y = 16; // COMPILER ERROR. . .implicit conversion
| Copyright © Karen Miller, 2007 |