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?
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 = newint;
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...