Re: dynamic cast from void*
On May 22, 7:40 pm, peter koch larsen <peter.koch.lar...@gmail.com>
wrote:
On 22 Maj, 23:38, p7ere...@gmail.com wrote:
Just checking and I can guess the answer, but what if I have an array
of void*. Into which I put a variety of typed pointer objects.
Normally, when I get out the object, I already know what type it is so
I can static_cast and am safe because it was exactly that same type
when I put it in.
But how powerful and safe is a dynamic_cast in this case. In some
exception handling code, I won't know the original type that I put
in. Can I dynamic_cast from the void* array element to a particular
fully derived type to see if it is that type?
So far as I can interpret the standard, when the value is of type
void*, the result will always be 0, so your dynamic_cast is non-
sensical. The relevant paragraph is [expr.dynamic.cast] - 5.2.7 in my
edition of a C++ draft.
The pointers in this case are pointers to class objects and only
happen to have been cast to void pointers. So the question is, can
dynamic_cast<> recover the class pointer types from these void
pointers?
According to ?5.2.7 answer is "yes" - but with two conditions: the
target class of the conversion must be polymorphic (that is, it must
have at least one virtual function) and the pointer being converted
(if not null) must point to an object of a polymorphic type (it does
not matter which polymorphic type). So in this case, as long as each
void pointer in the container points to an object of a polymorphic
class, than using dynamic_cast<> to convert the void pointers to class
pointers will work correctly. In particular, there is no requirement
that the polymorphic types of the class objects in the container must
be related to one another.
Greg
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]