Why is there a need of reinterpret_cast ?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • cplusplusbytes
    New Member
    • Nov 2009
    • 5

    Why is there a need of reinterpret_cast ?

    can someone give an example where static_cast fails during compilation and one would be forced to use reinterpret_cas t.
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    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.

    Comment

    • cplusplusbytes
      New Member
      • Nov 2009
      • 5

      #3
      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

      • weaknessforcats
        Recognized Expert Expert
        • Mar 2007
        • 9214

        #4
        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

        Working...