Connecting Tech Pros Worldwide Forums | Help | Site Map

type casting / conversion

Member
 
Join Date: Jun 2007
Posts: 66
#1: Oct 29 '07
i need someone to explain in the most primitive way possible, how to cast or convert between types, whats the difference between them, when do i use which, and why do i keep getting the cannot convert from type to type, and how would i do it optimally,

i mean all i need is standard cionversions between string, char, char array, float, double, etc, but i keep getting errors its driving me crazy!

thanks in advance,

Expert
 
Join Date: Aug 2007
Posts: 674
#2: Oct 29 '07

re: type casting / conversion


I assume you are using C++ (seems a bit obvious now, but you should mention what language you use). There's five different casting methods available to you. The first is the old C style casts, which you should avoid using. The other four are C++ style casts, which you should use. I won't bother to tell you what they are as this is simply a matter of googling and reading information on your own.

In fact, your entire question is really asking us to talk about the topic of casting. That's no longer a question. It's as meaningful a question as "what are C++ strings and tell me everything about them". Read up about C++ casting on Google. Or a good book like C++ Primer by Lippman.

Remember that casting does not involve any logic. Casting a string to an int does not mean you get a conversion from a string to an int. Casting is a way of overriding the compiler. You effectively say, hey I know what I'm doing here, treat this variable like another. Whether it is meaningful or not is unknown. It's up to you to know what you're doing.
Member
 
Join Date: Jun 2007
Posts: 66
#3: Oct 29 '07

re: type casting / conversion


sorry for the unprofessional way i asked the question, but the problem is i have read a lot about casting, i know how it works and what it does, but i keep getting errors, i might be having some kind of a block, but im just not getting it, if i may state the example im in at the moment that giving me the errors,

i have a *char coming from the strtok function, which i need to pass as an argument for a method in Maya's API, as a double


1>d:\maya work\api projects (c++)\retrievegeocmd\retrievegeocmd\retrievegeocmd cmd.cpp(164) : error C2440: 'static_cast' : cannot convert from 'char *' to 'double'

i tried every way of casting, and its not working,

thanks again for your time
Banfa's Avatar
AdministratorVoR
 
Join Date: Feb 2006
Location: South West UK
Posts: 6,167
#4: Oct 29 '07

re: type casting / conversion


Quote:

Originally Posted by askalottaqs

i have a *char coming from the strtok function, which i need to pass as an argument for a method in Maya's API, as a double


1>d:\maya work\api projects (c++)\retrievegeocmd\retrievegeocmd\retrievegeocmd cmd.cpp(164) : error C2440: 'static_cast' : cannot convert from 'char *' to 'double'

This is what oler1s was talking about, your first question was very generic and hard to answer, this however is quite specific (it is a single problem) and we can answer it (although posting the code lines that produce the error as well would have been better).


OK the short answer is that the compiler just can not cast between char * and double. They are incompatible types, the compiler just does not know how the treat the bits in the pointer as a double value.

However I think you are using the wrong approach to your problem. I am guessing you have a string of characters that represent a double value and you want to get that value in a variable of type double.

Casting is not the way to do this, casting is for use between variables of similar type so you can cast between all the numerical types (char, int, long, float double etc.) and you can cast between some pointer types e.g. any pointer casts to void *, you can cast pointers up and down class hierarchys.

You need to convert a character string (array of chars) into a double. In C++ the easiest way to do this is to import your array of chars into a stingstream type variable and the export them out as a double

Expand|Select|Wrap|Line Numbers
  1. #include <string>
  2. #include <iostream>
  3. #include <sstream>
  4.  
  5. using namespace std;
  6.  
  7. /* console cpp file */
  8. int main()
  9. {
  10.     char data [] = "1234.5";
  11.     double result;
  12.  
  13.     stringstream converter(data);
  14.  
  15.     converter >> result;
  16.  
  17.     cout << result << endl;
  18.  
  19.     return 0;
  20. }
Member
 
Join Date: Jun 2007
Posts: 66
#5: Oct 29 '07

re: type casting / conversion


cant thank you enough Sir! ::bow::
Moderator
 
Join Date: Mar 2007
Location: North Bend Washington USA
Posts: 5,366
#6: Oct 29 '07

re: type casting / conversion


To askalottaqs:

If you want a real earful about casting in C++, post again.
Member
 
Join Date: Jun 2007
Posts: 66
#7: Oct 30 '07

re: type casting / conversion


if it isnt too much trouble! wld love to, :D thnx
Moderator
 
Join Date: Mar 2007
Location: North Bend Washington USA
Posts: 5,366
#8: Oct 30 '07

re: type casting / conversion


Start with this:
Quote:

Originally Posted by weaknessforcats

int main()
{
const int Value = 10;

//TODO: Change Value to 20

}

But when you:
Quote:

Originally Posted by weaknessforcats

int main()
{
const int Value = 10;

//TODO: Change Value to 20

Value = 20;

}

it won't compile because Value is a constant. So you get sneaky:
Quote:

Originally Posted by weaknessforcats

int main()
{
const int Value = 10;

//TODO: Change Value to 20

int* ptr = &Value;
*ptr = 20;

}

but it still won't compile because ptr is a pointer to an int but &Value is the address of a constant int. If the compiler allows the assignment, then the fear is you will change the Value to something else. Hence, the compiler error.

But you persist.
Quote:

Originally Posted by weaknessforcats

int main()
{
const int Value = 10;

//TODO: Change Value to 20

int* ptr = (int*)&Value;
*ptr = 20;

}

Now it compiles because you lied to the compiler. Now you decided to display the Value and its address on the monitor:
Quote:

Originally Posted by weaknessforcats

int main()
{
const int Value = 10;

//TODO: Change Value to 20

int* ptr = (int*)&Value;
*ptr = 20;

cout << "Value: " << Value << '\n'
<< "Value using ptr: " << *ptr << '\n'
<< "&Value: " << &Value << '\n'
<< "ptr: " << ptr << endl;


}

On my system, I get:
Expand|Select|Wrap|Line Numbers
  1. Value:              10
  2. Value using ptr: 20
  3. &Value:             0013FF4C
  4. ptr:                    0013FF4C
  5.  
And you can see the 10 and the 20 are in the same memory location!

So now the part of your program that uses Value operates on 10 and the part that uses ptr operates on 20.

You see, the compiler never did change the const int. Instead, it made a copy for you to fiddle with. But when asked for the address, the compiled code reports the address of the original variable.

All casting involves the making of a copy of the object of the cast. You can fill your program with these hidden copies that are never seen yet your code depends on them.

This is the first in a long series of disasters caused by casting.
Member
 
Join Date: Jun 2007
Posts: 66
#9: Oct 31 '07

re: type casting / conversion


thank u for your extensive example, pretty confusing but i guess i got the point,

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?
Expert
 
Join Date: Aug 2007
Posts: 674
#10: Oct 31 '07

re: type casting / conversion


Quote:
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?
Well, here's a question in response. Had you not read this thread, what would you be using casting for?

I've seen casting misused by beginners, in commonly two ways.

The first is to do conversions. If you read this thread, you understand then that casting does not involve conversion. It is a tool at your disposal, to force the compiler to treat one variable type as another. C++ is a powerful, systems level language and you can therefore do so if you wish. Casting has its uses. One day you will reach a level when you will learn those underlying mechanics and will rely on casts. And it will have nothing to do with conversions.

The other way casting is commonly misused is beginners try to make their code compile. They find that somewhere, a variable needs to be of another type. They find that the compiler says x needs to be a char**. And they say, well, OK, let's cast x as a char**. Do you see the inherent problem in this?
Moderator
 
Join Date: Mar 2007
Location: North Bend Washington USA
Posts: 5,366
#11: Oct 31 '07

re: type casting / conversion


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:
Expand|Select|Wrap|Line Numbers
  1. class Date
  2. {
  3.      public:
  4.         //Conversion constructors
  5.         Date(string str);                //convert a string to a Date
  6.         Date(char* str);               //convert a C-string to a Date
  7.         Date(int arg);                  //conver an int to a Date
  8. };
  9.  
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:

Expand|Select|Wrap|Line Numbers
  1. class Date
  2. {
  3.      public:
  4.         //Conversion constructors
  5.         Date(string str);                //convert a string to a Date
  6.         Date(char* str);               //convert a C-string to a Date
  7.         Date(int arg);                  //conver an int to a Date
  8.  
  9.         //Conversion operators
  10.         operator string();             //convert a Date to a string object
  11.         operator char*();             //convert a Date to a C-string
  12.         operator int();                 //convert a Date to an int
  13. };
  14.  
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
Reply