Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does c++ forbid implicit conversion of void*?

Tags:

c++

c

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++?

like image 716
Sam Avatar asked Apr 18 '14 00:04

Sam


1 Answers

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.

like image 70
Brian Tracy Avatar answered Oct 20 '22 05:10

Brian Tracy