Casting

Discussion in 'C++' started by Asapi, Dec 17, 2003.

  1. Asapi

    Asapi Guest

    "Only static_cast can be used with value types; const_cast and dynamic_cast
    can only be used with pointers and references."

    Is this a correct statement?

    Can reinterpret_cast be used with references at all?

    const_cast casts away constantness. Can const_cast be used to cast back
    constantness if possible at all?

    Thanks!
     
    Asapi, Dec 17, 2003
    #1
    1. Advertising

  2. On Wed, 17 Dec 2003 20:20:41 +0000, Asapi wrote:

    > "Only static_cast can be used with value types; const_cast and dynamic_cast
    > can only be used with pointers and references."
    >
    > Is this a correct statement?
    >


    Yes.

    > Can reinterpret_cast be used with references at all?
    >


    Yes.

    > const_cast casts away constantness. Can const_cast be used to cast back
    > constantness if possible at all?
    >


    There is no need to "cast back constantness"; non-const pointers and
    references convert implicitly to const ones, e.g.:

    int x = 5;
    int* y = &x;
    const int* z = y;
     
    Simon Saunders, Dec 17, 2003
    #2
    1. Advertising

  3. Asapi

    Jerry Coffin Guest

    In article <tU2Eb.208540$Ec1.7546379@bgtnsc05-
    news.ops.worldnet.att.net>, says...
    > "Only static_cast can be used with value types; const_cast and dynamic_cast
    > can only be used with pointers and references."
    >
    > Is this a correct statement?


    It's half right. he part after the semicolon is correct, but the part
    preceding it is wrong. In addition to static_cast, you can use either a
    c-style cast or a ctor-style cast with a value type.

    > Can reinterpret_cast be used with references at all?


    Yes, though using the result is usually non-portable.

    > const_cast casts away constantness. Can const_cast be used to cast back
    > constantness if possible at all?


    You don't normally need an explicit cast to go from 'X' to 'X const'.
    Also note that const_cast can be used to cast away volatility.

    --
    Later,
    Jerry.

    The universe is a figment of its own imagination.
     
    Jerry Coffin, Dec 20, 2003
    #3
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Ben Nguyen
    Replies:
    6
    Views:
    18,805
  2. Toby
    Replies:
    3
    Views:
    3,088
    Mike Treseler
    Sep 7, 2005
  3. kevin
    Replies:
    11
    Views:
    5,809
    Andrew McDonagh
    Jan 8, 2005
  4. Wally Barnes
    Replies:
    3
    Views:
    528
    Wally Barnes
    Nov 20, 2008
  5. Sosuke

    Up casting and down casting

    Sosuke, Dec 20, 2009, in forum: C++
    Replies:
    2
    Views:
    564
    James Kanze
    Dec 20, 2009
Loading...

Share This Page