can someone give an example where static_cast fails during compilation and one would be forced to use reinterpret_cas t.
Why is there a need of reinterpret_cast ?
Collapse
X
-
-
Any time you need to take an integer type and interpret it as a pointer. This does not happen much on PC platforms (Linux, Windows Mac) because you rarely know the actual address of any bits of hardware.
However on embedded platforms it is something you do a fair bit because the various bits of hardware are often mapped into memory at a fixed address, you know the actual value of that address but to access the register at that address you often need to cast that number to a pointer.
reinterpret_cas t is one of those facilities of C++ that you should use sparingly and only when you really know it is the right thing to do. -
Looking for some simple example which I can run and see on linux machine, where static cast will fail and reinterpret case will work fine.Comment
-
static_cast will only work when you cast between related types. That is, casting a derived class pointer to a base class pointer.
reinterpret_cas t will permit a cast between any two pointers.
Therefore, if your static_cast is between unrelated types then it will fail at compile type but the same cast will succeed using a reinterpret_cas t.
Please note: ALL of this happens at compile time. There are no run-time checks.
It is dynamic_cast that is a static_cast with a run_time test.
You don't mention dynamic_cast so I am at a loss as to how the run-time applies to static_cast and reinterpret_cas t.Comment
Comment