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!

Can you cast from a pointer to a reference?
No, but you can initialize references from pointers provided that the pointed-to type (including constness) is the same.

Can you cast from a reference to a pointer?
No, but you can get a pointer from a reference using the address-of operator.

Can you cast from an object to a pointer?
No, but see the previous point.

Can you cast from an object to a reference?
No, but you can initialize references to objects.
closed account (S6k9GNh0)
helios is trying to say that your using the incorrect terminology. It's casting if your turning something into something else. Yes, pun intended because that's where it came from.

A pointer to a reference. NOTE that it didn't cast anything. It grabbed the data that was already available:
1
2
3
int * pInteger = new int;
int &myRef = *pInteger; //myRef now controls the allocated space of pInteger.
//I don't normally use references but this should be right... 


A reference to a pointer:
1
2
3
int myInt = 0;
int &myRef = myInt;
int * pInteger = &myRef; //myRef is a reference to myInt. It can also give you the adress since that's what a reference is after all. 


Object to pointer:
1
2
3
4
5
6
7
8
9
10
11
12
class MyClass
{
   public:
      MyClass() {}
      virtual MyClass() {}
};

int main()
{
   MyClass aClass;
   MyClass *pClass = &aClass;
}


I don't really think an example of the last one is needed...
thanks for both the replies!

I think it's slowly becoming clearer.

I was specifically interested in what you can and can't do with the static_cast and dynamic_cast operators...

So I think that's clearer now...

Cheers!
Topic archived. No new replies allowed.