Dynamic casting is intended to do the "dangerous work" more
safely. While a static_cast will simply cast to the derived
type regardless of whether the object is of that type,
[/QUOTE]
dynamic_cast<T>(pointer) is used with an object pointer, while
static_cast<T>(object) is the implicitly compatible conversion
and works with objects also. Am I right?
Both dynamic_cast and static_cast can be used on pointers and
references. (static_cast can also be used in a lot of other
cases.) When used on pointers or references:
-- static_cast allows moving up or down in the hierarchy (but
not sideways); it also allows converting to or from void*.
When moving down (Base* to Derived*), it makes no
verifications; if the object actually pointed to isn't a
Derived, anything can happen, so it is extremely dangerous
for this sort of casting. Note too that there are some
restrictions on static_cast when virtual base classes are
involved.
-- dynamic_cast only makes sense on pointers or references to
polymorphic types---otherwise, it only allows casting up
(Derived* to Base*), where it has exactly the same semantics
as static_cast. On pointers to polymorphic types, it allows
arbitrary navigation within the hierarchy, including
sideways. It verifies the type: if you dynamic_cast to
Derived*, and the pointer doesn't actually point to a
Derived*, it returns a null pointer (or raises an exception
if it is a reference cast). Except in very exceptional
cases (when the profiler says you must), you should use it
exclusively for down casting.
``is of that type'' means that
(*pointer) is declared as T or T's derived classes, right?
This cast fails if (*pointer) is declared as T's parent
classes or other un-related classes. Am I right?
I'm not too sure I understand. If pointer is of type Derived*,
dynamic_cast< Base* >( pointer ) always succeeds, of course,
returning a pointer to the Base sub-object of the Derived. If
pointer is of type Base*, dynamic_cast< Derived* >( pointer )
will return a null pointer if the actual object doesn't contain
an unambiguous Derived in its inheritance hierarchy, and a
pointer to the Derived if it does.
I read some past posts, some said dynamic_cast indicated flaw
in design
There is no requirement here for someone to be competent before
posting. dynamic_cast is easily abused, but there are cases
where it corresponds to the best design, and there are cases
where it represents the best engineering compromize.
Having a string of dynamic_cast usually is a sign of poor
design.