"johny smith" <pr**************@charter.net> wrote in message
news:10*************@corp.supernews.com...
I have never really understood the purpose of the void*.
I guess it is so different data types could for instance be passed into a
function. And then the function will re cast it to the correct data type?
I have an example here that does not seem to work.
I pass in an integer in one case and a float in another case.
When I pass the float, I would expect to get an answer of 5 but I get a
huge number that is not 5.
So, I was wondering if someone could tell me what I am doing wrong here?
Thanks.
I assume this is a strange way of using the void*, but I was just wanting
to practice using it in some way.
#include <iostream.h>
void f1( void* number );
int main()
{
int number;
float number2;
number2 = 5.25;
number = 5;
f1( &number );
f1( &number2 );
return 0;
}
void f1( void* number )
{
int* num;
num = (int*)number;
cout << *num << endl;
}
Well, first off, with C++ your use of void* has really diminished. Try
templates. For this sample:
template <class T>
void f1(T number)
{
cout << number;
}
Much safer and a lot more type strict. Furthermore, with void pointers, some
things get a bit crazy. You can't exactly just take a float pointer and cast
it to an integer pointer. To understand this, let's take the following
theoretical example:
The float you're passing in, in binary: 010101010010101101
(Note that's not a real number, just one I came up with)
The integer that results from it: 010101010010101101
(Note it hasn't changed)
Now let's do a REAL type cast (like float a = 5; cout <<(int)a;)
The float you pass in: 010101010101001
The integer that results: 01110101
(Note they are not the same)
This is the problem. Void pointers retain no knowledge of their type. As a
result, typecasting is not safe at all. Floats are interpreted differently
from ints, remember that. Because they are interpreted differently, it's a
big problem, and you're getting some really huge number. Templates are much
easier to work with and much safer.
Good luck
-- Matt
P.S. If you REALLY must use a pointer to void to cast something, try a
reinterpret_cast<>. It's just the C++ way of doing something insane like
that ... but I don't see any purpose for it -- ever.