CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Sep 2009
    Posts
    19

    Static/Dynamic casting and references/pointers

    Hi,

    I'm getting a bit confused while looking at static_cast and dynamic_cast while using references and pointers. I could really do with an idiots guide with plenty of examples to clear things up.

    I understand that:

    - static_cast has no RTTI checking (and so does not have the associated overhead)

    - dynamic_cast uses RTTI checking and so is safer, although this does incur an overhead at runtime

    - dynamic_cast can only be used with pointers and references

    Is there anything important I'm missing when comparing static vs dynamic casts?


    I understand what pointers and references are but could do with some clarification on the following points:


    Can you cast from a pointer to a reference?

    Can you cast from a reference to a pointer?

    Can you cast from an object to a pointer?

    Can you cast from an object to a reference?


    Is the main use of dynamic_cast then to cast base class pointers/references to derived class pointers/references and vice versa?



    Any help would be appreciated!

    Cheers!

  2. #2

    Re: Static/Dynamic casting and references/pointers

    There's a faq here that says 'how to deal with references'. That explains them pretty thoroughly.

    1. No.
    2. Sadly, no.
    3. You want to use object* objectPointer = &objectName, not casts.
    4. No, but you can declare a reference to an object.

    5. I mostly seem to use it for casting sideways.

  3. #3
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Seattle, WA
    Posts
    10,895

    Re: Static/Dynamic casting and references/pointers

    Quote Originally Posted by MisterEd View Post
    Can you cast from a pointer to a reference?
    No, but you can convert a pointer to its associated reference type using the dereference (*) operator.

    Can you cast from a reference to a pointer?
    No, but likewise, you can always take the address of the reference with & and thus get a pointer to the object.

    Can you cast from an object to a pointer?
    Only if the object defines an implicit conversion to that pointer type. For most cases, no.

    Can you cast from an object to a reference?
    There would be no point in doing so, although you can of course initialize a reference with an object.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured