Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting with multiple inheritance

If you have a void* pointer to Derived class that inherits from both BaseA and BaseB, how does the compiler cast the void* pointer to BaseA* (or BaseB*) without knowing that the void* pointer is of type Derived?

like image 338
Chazz Avatar asked Jul 25 '10 01:07

Chazz


2 Answers

It doesn't. The only guarantee when casting to and from a void* using a static_cast is:

A value of type pointer to object converted to "pointer to cv void" and back to the original pointer type will have its original value (C++03 §5.2.9/10).

For example, the following code is incorrect because the void* is cast to a type other than the original pointer type (the cast sequence is B1* -> void* -> B2*):

struct B1 { int i; };
struct B2 { int j; };

struct D : B1, B2 { };

D x;
B1*   b1ptr   = &x;
void* voidptr = b1ptr;
B2*   b2ptr   = static_cast<B2*>(voidptr);

Attempting to use b2ptr here would result in undefined behavior. The only type to which you can safely cast voidptr is B1*, since that is the type from which the void* was obtained (well, or to a char*, since anything can be accessed via a char*).

like image 122
James McNellis Avatar answered Oct 17 '22 13:10

James McNellis


The compiler doesn't cast the void* pointer to anything -- you, the programmer, do.

In order to do anything useful with a void* pointer, you need to explicitly cast it to a non-void* pointer, and if you're wrong about what type the pointer actually points to, you enter Undefined Behavior City.

like image 20
Tyler McHenry Avatar answered Oct 17 '22 13:10

Tyler McHenry