Why doesn't the compiler typecast the pointer and remove the error?
What's allowed is not dictated by the compiler but by the C++ standard and implicit conversions from a "pointer to double" to a "pointer to int" are not allowed by the standard. See, e.g., section 7.11 here.
There is nothing, in principle, that prevents you from coming up with a C++-like language where the above program is well-formed, once you specify what the semantics of the above assignment is.
As it is, I don't see any obvious meaning of what you are trying to write and I believe that if you try to formally specify what your expected behavior is, you'll run into problems.
Notice that there is no object of type int. What would be the reasonable thing to do? Should the compiler create one new int for you, initialize it with the result of a cast from double to int, and then assign the address to numPtr? Should that be allocated on the stack or on the heap? If it's on the stack, should using the pointer outside the current scope be illegal? If it's on the heap, who's responsible for free-ing the allocated memory?
How should changes on
num reflect on
*numPtr? Even worse,
numPtr is not a pointer to a constant int, so how should changes to
*numPtr reflect on
What if a new pointer, say of type short, is initialized to
If no new object is created, how do you reconcile the fact that two pointers of different (and incompatible) types point to the same memory address? (Recall that you can do
numPtr = reinterpret_cast<int*>(&num); but dereferencing
numPtr violates aliasing rules).