How to do safely convert for multiple inheriting

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

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.

//wrong
}
}


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 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 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 on other sites
No, it should work to convert to any type, regardless of the initial type.

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).

• 10
• 17
• 9
• 13
• 41