Michael Doubez wrote:
> On 4 mar, 09:46, Michael Tsang <mikl...@gmail.com> wrote:
>> DeMarcus wrote:
>>> Michael Doubez wrote:
>>>> On 3 mar, 19:08, "Leigh Johnston" <le...@i42.co.uk> wrote:
>>>>>> I hinted that with dynamic_cast<void*>() you get a pointer on the most
>>>>>> derived class. IMO, this is what you are looking for. In the example:
>>>>>> void* pa1 = static_cast<A*>(p2);
>>>>>> void* pa2 = static_cast<A*>(p3);
>>>>>> void* pv1 = dynamic_cast<void*>(pa1);
>>>>>> void* pv2 = dynamic_cast<void*>(pa2);
>>>>>> assert( pv1 == pv2 && "Should Succeed" );
>>>>> This won't work as dynamic_cast requires polymorphic types, pa1 and pa2
>>>>> are void* pointers (not polymorphic), if you meant pa1 and pa2 to be A*
>>>>> pointers
>>>> Yes, that's what I meant.
>>>>> it still won't work as A is not polymorphic.
>>>> What do you mean ? A doesn't need to be polymorphic for dynamic_cast<>
>>>> to work.
>>> Actually, yes. According to the standard, it says nothing about that
>>> demand, but according to my compiler (gcc 4.4.1) it gives an error if A
>>> is not polymorphic.
>>> Something is wrong, I agree. Is it because there is no vtable in A?
>> The standard does say that to cast from base to derived needs a virtual
>> function in base. (ISO/IEC 14882:2003 Section 5.2.7 Dynamic cast
>> [expr.dynamic.cast]
>>
>> 1 The result of the expression dynamic_cast<T>(v) (omitted)
>> 2 (omitted)
>> 3 If the type of v is the same as the required result type (omitted), or it
>> is the same as R except that the class object type in R is move cv-qualified
>> than the class object type in v, (omitted)
>> 4 (omitted)
>> 5 If T is "pointer to cv1 B" and v has type "pointer to cv2 D" such that B
>> is a base class of D, (omitted)
>> 6 Otherwise, v shall be a pointer to or an lvalue of a *polymorphic* type.
>
>
> OK. The RTTI information is not generated if A is not polymorphic (or
> without a specific compiler option or pragma) and dynamic_cast<>()
> will fail.
>
> Well. Easy enough to fix - use a virtual destructor.
>
Yes, thanks!
|