Quote:
Originally Posted by askalottaqs
and sorry for being too persistant, but i need to ask something, if u say that type casting can be disastrous what should i be using instead?
To answer this you need to be clear on two things:
1) A cast is forcing one type to be another type over the compiler's objections.
2) A conversion is a orderly construction of using an object of another type.
With that in mind, C++ has
conversion constructors. These are constrcutors that have only one argument. The object being constrcuted is a conversion of the object used as the argument:
-
class Date
-
{
-
public:
-
//Conversion constructors
-
Date(string str); //convert a string to a Date
-
Date(char* str); //convert a C-string to a Date
-
Date(int arg); //conver an int to a Date
-
};
-
These constructors will convert these types to a Date where no cast on earth will do it.
So, the conversion constructor converts and object of some type to the class type.
To go the other way, you use
conversion operators. A conversion operator is a member function that converts the class type to the type of the conversion operator:
-
class Date
-
{
-
public:
-
//Conversion constructors
-
Date(string str); //convert a string to a Date
-
Date(char* str); //convert a C-string to a Date
-
Date(int arg); //conver an int to a Date
-
-
//Conversion operators
-
operator string(); //convert a Date to a string object
-
operator char*(); //convert a Date to a C-string
-
operator int(); //convert a Date to an int
-
};
-
These conversion operators allow a Date object to become another type.
Again, these functions convert the Date into the type of the operator function using code you write. So, this is not forcing anything.
A conversion operator can convert objects to another type when no cast can do it.
Anytime you cast in C++ a read flag should appear before your eyes with the words
Wrong Way on it.
Now, there are times you need to cast:
1) working with relic C functions that have void* arguments
2) maybe doing file I/O (but maybe not)
3) maybe writing a template