|
-
October 16th, 2009, 11:26 AM
#1
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!
-
October 16th, 2009, 03:04 PM
#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.
-
October 16th, 2009, 03:26 PM
#3
Re: Static/Dynamic casting and references/pointers
 Originally Posted by MisterEd
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
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|