colourfulbananas wrote: |
---|
"But with a pointer can you pass any type of variable by reference?" |
With a
void pointer, yes, you can. However, if a pointer is of type
float, it can only point to a
float and nothing else unless it's converted. Of course, since
void allows you to point to anything, the compiler will not allow you to write to the object it points to unless you tell the compiler what it's pointing to. For example:
1 2 3 4 5
|
void SomeFunction(void *Data)
{
*Data = 10; // A
*(static_cast<int*>(Data)) = 10; // B
}
|
A) This is an error. Since
Data can be pointing to anything, the compiler will not know what it's pointing to. Thus, the compiler will be clueless as to how the 10 should be stored in
Data. This brings use to B.
B) Here, we're using
static_cast to convert
Data to a pointer to an
int. This informs the compiler how it should store the 10 in
Data. Note that casting creates another pointer to the same location as the pointer you gave it. In this case, it returns a pointer to an
int which points to the address pointed-to by
Data. Casting, however, does not affect the pointer given to it.
Wazzak