- Implicit type conversion is performed by the compiler in
expressions with mixed data types
- Promotions and demotions are performed based on the following
hierarchy:
int < long < unsigned < unsigned long < float < double <
long double
All char, unsigned char, short and unsigned short are promoted to
int regardless of whether the expressions has mixed data types or not
char v1 + short v2 / int v3; // Result is an int
unsigned v1 * 7 + int v2; // Result is unsigned
int v = 42.6; // Truncated at decimal
unsigned char ch = -427.95; // Double demoted to unsigned char
- Explicit casting is commonly used to override implicit conversions. e.g.,
(int) CharVar; // C type casting
int (CharVar); // Casting like a function call - only in C++
- When user defined types are used in expressions containing mixed data types,
conversions must be defined by the class developer using either a conversion
operator, or an appropriate constuctor
- A conversion operator is a special member function that specifies the implicit
conversion of a class object to another type. For example:
class FeetDist{ ... }
class MeterDist{
public:
operator int() { return length; } // Coversion operator from MeterDist to int
operator FeetDist(); // Coversion operator from MeterDist to FeetDist
private:
int length;
};
int main(){
MeterDist d;
int i = d; // Operator int is called for d
int j = int(d); // Explicit call to conversion operator
- The conversion operator must be a member function
- The conversion operator cannot have an argument list or a return type
- The user can explicitly call user defined conversions in the same way as
built-in conversions are called (casting)
- The compiler will implicitly invoke a user defined conversion function
whenever a class object is present in an expression and it is not of the
correct type
- User defined conversions will not be "chained" by the compiler
- The compiler uses standard conversions and promotions in conjunction
with user defined conversions
- Any constructor that receives a single argument can also be used for
implicit conversion to the class being constructed. For example:
String::String(char* str){
name = new char[strlen(str) + 1];
strcpy(name, str);
}
- A user defined conversion that provides the exact conversion will be used
instead of one that requires additional standard conversions
- If enough conversion functions are defined, the ambiguous operations
could occur. For example:
class Angle{
public:
operator float() { return value; }
Angle(float f = 0.0) : value(f) {}
Angle(Angle& A) : value(A.value) {}
friend Angle operator+(const Angle& , const Angle& );
private:
float value;
};
int main)(){
Angle a;
float f = 10.0;
Angle a1 = a + f; // Error, ambiguous (float + float) or (Angle + Angle)
return 0;
}