In C, we can convert void*
to any other pointers.
But C++ forbids it.
int *a = malloc(4);
leads to this error:
invalid conversion from ‘void*’ to ‘int*’ [-fpermissive]
Are there any latent dangers here in c++?
Are there any examples of c++?
The reason you cannot implicitly convert from void *
is because doing so is type unsafe and potentially dangerous. C++ tries a little harder than C in this respect to protect you, thus the difference in behavior between the two languages.
Consider the following example:
short s = 10; // occupies 2 bytes in memory
void *p = &s;
long *l = p; // occupies 8 bytes in memory
printf("%ld\n", *l);
A C compiler accepts the above code (and prints garbage) while a C++ compiler will reject it.
By casting "through" void *
, we lose the type information of the original data, allowing us to treat what in reality is a short
as a long
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With