Sign in to follow this  

How to do safely convert for multiple inheriting

This topic is 4353 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

As the title, how could I do this if I do not the the type? For example:
class Foo
{
  ...
}

class Bar
{
  ...
}

class IClass : public Foo,
               public Bar
{
  ...
}

void main()
{
    //style 1.
    {
       IClass *p = new IClass;
       
       //Correct
       Foo *pFoo = p;
       Bar *pBar = p;
    }

    //style 2.
    {
       IClass *p = new IClass;
      
       //Convert to void,
       //So the following two conversion will lost the type info.
       void *pAddress = (void*)p;
       
       //wrong
       Foo *pFoo = (Foo*)pAddress;
       Bar *pBar = (Bar*)pAddress;
    }
}

Compare style1 and style2. I found that in the first style, compiler will automatic calculate the offset for each base class and then successfully assign the correct address for each variable. But for the second style, IClass *p has been convert to a void* pointer, so the compiler cannot get its original type info. So my question is that, if I only get the address, how can I do a safely conversion? Since, some time, we cannot get the child classes' type info in base class. How could I do it? Thanks in advance!

Share this post


Link to post
Share on other sites
The only way to perform safely any conversion that is not a subtyping conversion is to enable RTTI, and use dynamic_cast. The conversion will be done automatically at the correct offset in all cases.

Share this post


Link to post
Share on other sites
OK, thanks, it do works on my computer.

Another question, dynamic_cast< TYPE >( Expression )

so, if the expression is a void * pointer, I have to convert it to a relative data type, right?

Share this post


Link to post
Share on other sites
However, you should be careful with void* in general in C++; there's rarely a good reason to use it (except to deal with someone else's legacy C code).

Share this post


Link to post
Share on other sites

This topic is 4353 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this