According to this site:
You cannot implicitly assign from a void*
to any other type. For instance, the following is perfectly valid in C (in fact, it's arguably the preferable way of doing it in C)
int *x = malloc(sizeof(int) * 10);
but it won't compile in C++.
The explanation from Bjarne Stroustrup himself is that this isn't type safe. What this means is that you can have a void*
that points to anything at all, and if you then assign the address stored in that void* to another pointer of a different type, there isn't any warning at all about it.
Consider the following:
int an_int;
void *void_pointer = &an_int;
double *double_ptr = void_pointer;
*double_ptr = 5;
cout<<an_int<<endl;
When you assign *double_ptr
the value 5, it's writing 8 bytes of memory, but the integer variable an_int
is only 4 bytes. So when you prints the value of an_int
variable, output will be 0 because according to 4 bytes compiler select least significant bits of 5(5.000..) that is 0.
In C++, forcing a cast from a void pointer makes the programmer pay attention to these things. So in that language implicitly type conversion from void *
is forbidden to give stronger type safety.
but I am literally confused when I'd cast void *
to double *
in this example like:
int an_int;
void *void_pointer = &an_int;
double *double_ptr = (double *)void_pointer;
*double_ptr = 5;
cout<<an_int<<endl;
The output will remains same that is 0.
So what role type-safety play's here ? and what exactly Bjarne Stroustrup's explained about type-safety ?