C++ Casting (re-interpret cast)

This is a discussion on C++ Casting (re-interpret cast) within the C++ Programming forums, part of the General Programming Boards category; Hi there, I find dynamic_cast really useful, and want to know about the others. reinterpret_cast looks interesting, but no matter ...

  1. #1
    Code Monkey Davros's Avatar
    Join Date
    Jun 2002
    Posts
    812

    C++ Casting (re-interpret cast)

    Hi there,

    I find dynamic_cast really useful, and want to know about the others.

    reinterpret_cast looks interesting, but no matter how much I read about it, I have no idea what it does. I.e. what's the difference between it and static_cast etc.

    Can someone give me a really noddy explanation of the difference between reinterpret_cast, const_cast and static_cast.

    Thanks
    OS: Windows XP
    Compilers: MinGW (Code::Blocks), BCB 5

    BigAngryDog.com

  2. #2
    Registered User
    Join Date
    Nov 2001
    Posts
    1,348
    reinterpret_cast() is for converting between different types. One example is converting an int to a char.

    Kuphryn

  3. #3
    Code Monkey Davros's Avatar
    Join Date
    Jun 2002
    Posts
    812
    Thanks for the reply. Are you saying that an exception will be thrown if the char cannot be converted without a loss of precision?
    OS: Windows XP
    Compilers: MinGW (Code::Blocks), BCB 5

    BigAngryDog.com

  4. #4
    &TH of undefined behavior Fordy's Avatar
    Join Date
    Aug 2001
    Posts
    5,789
    There are 4 standard casts.

    dynamic_cast is exclusive to C++ and allows you to "castup" from a base class to a derived class. It throws an exception or returns NULL depending on if you are using a reference or a pointer.

    The other 3 are derivatives on the standard C style casts.

    static_cast is a pretty safe little cast for converting things like ints to doubles etc...casts that wont cause any hassle

    const_cast casts away the const quality of a variable and is handy in some tight circumstances when you know what you are doing

    reinterpret_cast is the cast you use when you are doing something potentially dangerous & out of the ordinary that you are forced to do like casting a pointer to a differnt pointer or (more likely for winapi) casting an intergal to a function pointer (IE LONG to a WNDPROC)

    I always use them as they force me to think what I'm trying to do

  5. #5
    Toaster Zach L.'s Avatar
    Join Date
    Aug 2001
    Posts
    2,686
    static_cast is the normal sort of conversion. (I can explain it better, but intuitively, it does what you'd expect). A meaningful conversion must exist, though. reinterpret_cast simply reinterprets the bits as the target type.

  6. #6
    Code Monkey Davros's Avatar
    Join Date
    Jun 2002
    Posts
    812
    OK. I follow so far, but this is where I start to get all confused...

    Under what circumstances does reinterpret cast fail, and how will it fail. For example, is a runtime check performed to determine that the value stored in an integer is a valid WNDPROC pointer?

    If so, would I be right in thinking it is like dynamic_cast except there is no requirement for a virtual base class. If so can I use it instead of a dynamic_cast? Will it fail where dynamic_cast fails?

    If I should only use static_cast for things like ints to doubles, what's the advantage of using it over the following:

    int a = 5;
    double b = a;
    OS: Windows XP
    Compilers: MinGW (Code::Blocks), BCB 5

    BigAngryDog.com

  7. #7
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,893
    Strictly seen, the only cast that can "fail" is dynamic_cast, because only dynamic_cast does any runtime checks.
    The other casts may not compile if you use them incorrectly, but once compiled they don't fail as in "throw an exception". They might produce garbage or crash the app (e.g. when you cast an integer to a pointer and dereference it when there's no justification for doing so).

    int to double needs no cast, and using static_cast is overkill. You might want to use it to point out the cast, but usually you only use it when you, for example, want to select a particular overload of a function.
    double to int on the other hand will generate a warning on most compilers unless you do it explicitely with a static_cast.
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  8. #8
    Toaster Zach L.'s Avatar
    Join Date
    Aug 2001
    Posts
    2,686
    reinterpret_cast should not fail. What is more likely, however, is that the object you converted to is complete garbage, and when you use it, a runtime error will occur. Avoid using it in place of dynamic_cast... That is a bad idea. If you need to convert between objects, it is safer to either define explicit conversion functions, or conversion operators. Sometimes it is necessary to use (as in Fordy's example, converting an integer to a pointer), but remember that you may very well end up with garbage if you are not very careful.

  9. #9
    &TH of undefined behavior Fordy's Avatar
    Join Date
    Aug 2001
    Posts
    5,789
    Quote Originally Posted by Davros
    OK. I follow so far, but this is where I start to get all confused...

    Under what circumstances does reinterpret cast fail, and how will it fail. For example, is a runtime check performed to determine that the value stored in an integer is a valid WNDPROC pointer?
    It can fail (compile time) if the you are doing something silly like casting a whole object to an int. It can often issue warnigns for less troublesome size differences.

    Quote Originally Posted by Davros
    If so, would I be right in thinking it is like dynamic_cast except there is no requirement for a virtual base class. If so can I use it instead of a dynamic_cast? Will it fail where dynamic_cast fails?
    No..dynamic cast will fail if the pointer is not a base ptr/ref to a derived pointer. It only really works for inheritance etc. You can use reinterpret_cast for this but if you are not carefull you will likely get a crash

    Quote Originally Posted by Davros
    If I should only use static_cast for things like ints to doubles, what's the advantage of using it over the following:

    int a = 5;
    double b = a;
    It's a little more handy than that

    Have a look at this
    Code:
    #include <iostream>
    
    struct foobar;
    void Edit(foobar* f);
    
    struct foobar
    {
    	int m_i;
    	foobar():m_i(64){}
    };
    
    void Edit(foobar* f)
    {
    	std::cout << "Edited to - " << ++(f->m_i) << std::endl;
    }
    
    void PrintPointer(long PointerAsVal)
    {
    	std::cout << "Address - " << PointerAsVal << std::endl;
    }
    
    int  main (int argc, char **argv)
    {
    	const foobar a;
    	std::cout << "Value as intr - " << a.m_i << std::endl;
    	std::cout << "Value as char - " << static_cast<char>(a.m_i) << std::endl;
    	Edit(const_cast<foobar*>(&a));
    	PrintPointer(reinterpret_cast<long>(&a));
    }

  10. #10
    Registered User
    Join Date
    Jul 2004
    Posts
    12
    which would you use to cast a SAFEARRAY into an integer array?

  11. #11
    &TH of undefined behavior Fordy's Avatar
    Join Date
    Aug 2001
    Posts
    5,789
    Quote Originally Posted by So and So
    which would you use to cast a SAFEARRAY into an integer array?

    You wouldnt do that with a cast...you would use an API

  12. #12
    Code Monkey Davros's Avatar
    Join Date
    Jun 2002
    Posts
    812
    Mmmm. [Smoke & burning smell emitting from ears]. So...

    static_cast should be used in the following circumstance:

    double a = 5.0;
    int b = static_cast<int>(a);

    in place of:
    int b = (int)a;

    And reinterpret_cast used:

    MYCLASS* b = reinterpret_cast<MYCLASS*>(a); // where a is pointer to some other object

    instead of:
    MYCLASS* b = (MYCLASS*)a;

    I.e. they do exactly the same as C style casts, except to distinguish between pointers and static objects?
    OS: Windows XP
    Compilers: MinGW (Code::Blocks), BCB 5

    BigAngryDog.com

  13. #13
    &TH of undefined behavior Fordy's Avatar
    Join Date
    Aug 2001
    Posts
    5,789
    >>I.e. they do exactly the same as C style casts, except to distinguish between pointers and static objects?

    Not exactly. Think of them on a level of safety..start with static_cast...if that doesnt work then your likely doing something a little dangerous (IE casting an intergal to a pointer or likewise)...so const_cast if you are editing a const object or reinterpret_cast if it's a more unsafe cast that static_cast wont touch.

  14. #14
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,893
    const_cast isn't for editing const objects, it's for passing const objects or pointer to poorly written APIs.

    Well, that's my opinion anyway. Editing const objects is bound to make difficulties one way or the other.
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  15. #15
    Code Monkey Davros's Avatar
    Join Date
    Jun 2002
    Posts
    812
    >Not exactly. Think of them on a level of safety..start with static_cast...if that doesnt work then your likely doing something a little dangerous

    When you say a 'level of safety', do you mean I will get compiler warnings rather than any runtime change in behaviour?.
    OS: Windows XP
    Compilers: MinGW (Code::Blocks), BCB 5

    BigAngryDog.com

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Including The Right DLLs
    By bumfluff in forum Game Programming
    Replies: 8
    Last Post: 12-28-2006, 02:32 AM
  2. Replies: 28
    Last Post: 07-16-2006, 11:35 PM
  3. Converting Double to Float
    By thetinman in forum C++ Programming
    Replies: 7
    Last Post: 06-17-2006, 02:46 PM
  4. errors in class(urgent )
    By ayesha in forum C++ Programming
    Replies: 1
    Last Post: 11-10-2001, 09:14 PM
  5. errors in class(urgent)
    By ayesha in forum C++ Programming
    Replies: 2
    Last Post: 11-10-2001, 05:51 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21