Understanding C++ Pointer Assignments
Explanation:
Given the declarations:
double* dp = new double(3);
void* vp;
int* ip;
The compiler will raise errors for the following assignments:
- dp = vp; - Cannot assign a `void*` pointer to a specific type without casting.
- ip = dp; - Cannot directly assign a pointer of type `double*` to `int*` without a cast.
- dp = ip; - Unable to assign an `int*` pointer to a `double*` pointer without a cast.
- ip = vp; - Similar to the first case, cannot assign `void*` to `int*` without a cast.
However, the compiler will not complain about:
- ip = (int*) vp; - This is an explicit C-style cast.
- ip = reinterpret_cast
(dp); - This is a reinterpret cast that forces a bit-by-bit conversion.
The valid C++ style casts are explicit and checked during compile-time, explaining why `static_cast` does not work for casting from one pointer type to an unrelated pointer type.
Regarding the value of *ip, it will not be 3 after any of the assignments mentioned above because the data representation of a `double` and an `int` is different. Thus, *ip will likely hold a nonsensical or undefined value after such a cast.