Reputation: 5772
I have a class hierarchy that involves virtual functions, multiple inheritance, but not virtual inheritance. The whole hierarchy roots in a base class B
. A class appears at most in the hierarchy.
Now, I am using a library where I can only pass and receive back void*
(some “handles” basically).
In which circumstances is it safe/legal/defined to cast between instances of my hierarchy and void*
?
Should I always upcast to B*
before passing void*
and vice versa?
Will (D*) (B*) (void*) (B*) d
be equal to d
if d
is an instance of D*
and D
a subclass of B
?
Upvotes: 1
Views: 458
Reputation: 119877
You must cast from void*
to the same exact type you cast to void*
to begin with. This is guaranteed to be safe. Other casts from void*
lead to UB.
Once you have a non-void pointer, normal casting rules for pointers of a class hierarchy apply.
Using your example,
(D*) (B*) (void*) (B*) d
is OK, but
(D*) (void*) (B*) d
(B*) (void*) d
are not.
Upvotes: 5