Jump to content
  • Advertisement
Sign in to follow this  
KevinLee

How to do safely convert for multiple inheriting

This topic is 4603 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
Advertisement
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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!