Type conversion is executing code that you write to orderly convert one type into another.
C++ has two features for this a) conversion constrcutors, b) conversion operators. Conversion constructors convert a type to your class type and conversion operators convert your class type into another type.
A conversion constrcutor is a constructor that has only one argument.
Assume a class Date:
-
class Date
-
{
-
public:
-
Date(string arg); //make a Date from a string
-
Date(const Date& arg); //make a Date from another Date
-
Date(const char* arg); //make a Date from a C-style string
-
Date(int arg); //make a Date from an integer.
-
};
-
;
In these cases, a Date object can be created and initialized using code that you have written. This is a type conversion.
A typecast is a direction by you to the compiler to change a type in such a way as to violate the rules of C++.
-
Date dt("12/21/2007");
-
-
int* ptr = reinterpret_cast<int*> (&dt);
-
Here dt is a Date and the cast tells the compiler to treat the Date as an integer when you use the ptr pointer. This is nonsense, but it is valid. C++ let's you do stuff like this in case you have some emergency and this is the only way to solve it. Unfortunately, typecasting is often used by programmers who don't understand what they are doing and have to keep forcing the compiler to accept their poor code.
Almosty all typecasting can be avoided if you use a conversion operator. A conversion operator is like your constructor. It is code you write to orderly convert your class into something else.
In the example above, if your Date class looked like this:
-
class Date
-
{
-
public:
-
Date(string arg); //make a Date from a string
-
Date(const Date& arg); //make a Date from another Date
-
Date(const char* arg); //make a Date from a C-style string
-
Date(int arg); //make a Date from an integer.
-
-
operator int*(); //make an int* from a Date
-
};
-
;
The operator int*() is a member function that the compiler can call when a Date needs to be converted into another type. If you have this member function, the compiler will call it to do the reinterpret_cast example.