alg wrote:
> dynamic_cast<> comes in play when to perform conversion from a pointer
> to a base class to a pointer to a derived class.
>
> I don't understand:
>
> 1. why this is so necessary since we can either use an explicit cast
> or use "static_cast<>" (Can we?)?
To find out if the object can really be used as one of the specified
derived class.
Btw, your terminology "explicit cast" is not very good. First, all casts
are explicit, since that's their nature. A cast is what you write into
your code to explicitly invoke a conversion. This of course also means
that dynamic_cast _is_ an "explicit cast", just like all other casts.
> 2. the above said conversion is dangerous, using explicit conversion.
Casts should be avoided if possible, but if you need a downcast on
polymorphic types, dynamic_cast is the safest one.
> Does this mean that using dynamic_cast<> will be safer.
Than what? static_cast? Depending on the situation, it can be safer.
> How this could be?
dynamic_cast returns 0 (when used on pointers) or throws an exception
(when used on references) if the object is actually not of the
specified class.
> 3. Is static_cast<> at compiling time and dynamic_cast<> realized at
> runtime?
Yes.
|