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 "rein开发者_开发问答terpret_cast"? please advice me
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.
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.
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.
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.
精彩评论