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 19:49:59 +0300

Maxim Yegorushkin wrote:
> [...]
>> 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.
>
> I would redesign my hierarchy so, that dynamic_cast would be enough.

I'm open for any suggestions but don't know if I can simplify it. If you 
have a function like this:

base *foo();

which returns a level2 class but you know that level2 classes are grouped 
then you try to find their parent classes (level1) if in the current 
function you don't need to work with level2 classes (of course there are 
other functions which need to; thus I can't get rid of any level).

It's not an option either to change the return type of foo() as there are 
quite a lot of functions which all work with base classes. It must be 
possible to nest them like in bar(foo()). No matter what foo() returns bar() 
must be able to work with. And no matter what function is nested it must 
return base* to bar().

> [...]
> This is a title of a frequently asked question. The answer is given
> fow to make it work. If you can follow the first advise, which is
>
> <q>
> For a program which is linked against a shared library, no additional
> precautions are needed
> </q>
>
> then no other action is required.

That's what I have and how I ran into this problem: It's a console program 
linked to a shared library.

>> 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;
>> }
>
> You could find more help if you posted simplified complete code that
> reproduces what you are observing.

I had created a small test case but unfortunately it worked. The project I 
port is too large - it would take some time to track this down which I don't 
have currently.

> It might be that you derive privately from your base (class A : B {};)
> . dynamic_cast in this case does not work, reinterpret_cast does work
> if your base class is first in the list of the base classes.

But why does it all work then when I link statically?

Boris 




reply via email to

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