views:

237

answers:

4

Hi all,

i want to cast from upper class pointer to lower class i.e from the base class pointer to derived class pointer.

Should i use "Dynamic_cast" or "reinterpret_cast"? please advice me

+11  A: 

Don't use reinterpret_cast - either use static_cast or dynamic_cast. If you're sure that the pointer is to exactly that derived class object use static_cast, otherwise use dynamic_cast (that will require the base class to be polymorhic) and check the result to ensure that the pointer is indeed to the class you want.

sharptooth
you mean, for upward casting as well as downward casting, static_cast is better? or when do i have to use static_cast or dynamic_cast?
Shadow
You don't need to use a cast at all for "upward casting". `Derived *dptr = something; Base *bptr = dptr;` works fine.
Steve Jessop
Ok, fine.. if i am sure that i am going to do upper cast, i will not use any casting, for downward casting always i preffer static_cast..but what is the use of Dynamic_cast? when i have to use "reinterprit_cast too?
Shadow
`dynamic_cast` is for when you don't know whether the thing pointed to by your `Base*` really is a `Derived` object, and you want to find out (and get a `Derived*` pointer if so). It's rarely needed. `reinterpret_cast` should never be used for casting between related pointer types. In certain circumstances (such as multiple inheritance) it gives the "wrong" answer, for instance gives you a `Derived*` pointer that will crash if you use it as a `Derived*`.
Steve Jessop
In case of upcast the implicit conversion that "just works" is in fact the static_cast - see this great answer http://stackoverflow.com/questions/2198255/which-kind-of-cast-is-from-type-to-void/2205137#2205137.
sharptooth
@sharptooth: well, it has the same effect as the static_cast, because static_cast is defined to be able to perform standard conversions: compare 4.10/3 with 5.2.9/2. The reason I say you don't need a cast is just that a cast is by definition an explicit conversion, and this is an implicit conversion. But yes, static_casts between types that can be implicitly converted, and implicit conversions, are in fact the same thing.
Steve Jessop
+6  A: 

It depends on what you know about the pointer.

If you know for sure that the pointer you have is of a child type, you can static_cast<> it safely.

If you don't know for sure, just go with dynamic_cast<> but this has a cost and is slower.

ereOn
A: 

To add to Ereon's answer: And if you do not know the type use dynamic_cast to do a run time type check by catching the bad_cast exception.

RdM
If he's casting pointers, it won't throw a bad_cast.
anon
But he will get a null pointer if it's not of the dynamic_cast type.
foxwoods
+2  A: 

reinterpret_cast<> is a last resort and should be avoided.

In Qt, if casting between QObjects, use qobject_cast<>. It's semantically like dynamic_cast but has no issues with dll boundaries etc.

Frank