on type casting

why exactly c++ has kept constriant on void pointers.
suppose

int a=2;
int *p=&a;
void *voidpointer=p;
int *another=p1; //why we have to explicitly cast to (int *) according to c++

and also tell me why we cant perform dereferencing on void * pointers?

with regards,
vishnu
The void pointer doesn't carry any information about what type it points to so the compiler has no way of knowing if the cast is correct or not.
1
2
3
int i = 1;
void* vp = &i;
double* dp = vp; // This is wrong because the pointer is in fact pointing to an int 

The compiler doesn't do the cast implicit because it doesn't know if it's safe. If you want to cast the void pointer you have to do it explicitly but then you know that you as a programmer is responsible that the cast is correct. You can't count on the compiler to tell if something goes wrong.

Note that void is not a type so dereferencing a void* would give you what? I don't think there is a good answer so better not allow it.
Last edited on
Topic archived. No new replies allowed.