help-gplusplus
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: dynamic_cast from base to another parent of derived class


From: Boris
Subject: Re: dynamic_cast from base to another parent of derived class
Date: Wed, 4 Oct 2006 11:49:11 +0300

Maxim Yegorushkin wrote:
> [...]
>
> Why not just:
>
>    if(level2 const* l2 = dynamic_cast<level2 const*>(&b))
>    {
>        // no need comparing typeinfo's
>    }
>
> ?

I want to cast to a level 1 class which is a parent of several level 2 
classes. Otherwise you are right - I could cast to the actual type directly. 
The real code looks more like this:

if (typeid(b) == typeid(level2a) ||  typeid(b) == typeid(level2b) || 
typeid(b) == typeid(level2c))
{
  const level1 *l1 = dynamic_cast<const level1*>(&b);
}

Class level1 is the parent of all the level2 classes. I have to check for 
several types but don't need to write the same code then at least for all 
the level2 classes.

>> It looks like a problem with g++. The code I was talking about is in
>> a shared library. When I link the executable statically dynamic_cast
>> works. When I use however the shared library dynamic_cast returns 0.
>> Same code but different behavior due to linking.
>>
>> There is a section "dynamic_cast, throw, typeid don't work with
>> shared libraries" at http://gcc.gnu.org/faq.html#dso.
>
> I wonder how you reached such a conclusion. Where on that page do they
> say it does not work?

The title is pretty clear I think: "dynamic_cast,throw, typeid don't work 
with shared libraries". :-) They are talking about template instantiations, 
vague linkage, not an exhaustive list, namesspaces etc. This all doesn't 
sound like adding a linker switch fixes all your problems. This sounds like 
be ready for all kind of problems.

Anyway if I can downcast to the actual type and then back to its parent with 
the following code (no compilation error, no runtime error) why should a 
dynamic_cast to the parent l1 not work?

if (typeid(b) == typeid(level2))
{
  const level2 *l2 = dynamic_cast<const level2*>(&b);
  const level1 *l1 = l2;
}

Boris 




reply via email to

[Prev in Thread] Current Thread [Next in Thread]