I have a type eraser with the following inheritance structure:
Holder
/ | \
| | |
Holder_A_1 Holder_B_1 Holder_C_1
| | ...
Holder_A_2 Holder_B_2
... ...
| |
Holder_A_base Holder_B_base Holder_C_base
| | ...
Holder_A_base_2 Holder_B_base_2
... ...
| | |
Anchor Anchor Anchor
(The Anchor base class is repeated on purpose.)
Upon the object construction I construct a Holder object and cast it to Anchor* for storage and deletion. The cast is done via Holder_A_base*
for disambiguation: static_cast<Holder_A_base*>(static_cast<Anchor*>(this))
My question is: is it legal to static_cast
from Anchor*
(constructed as explained above) to Holder_B_base*
if I know for a fact that Holder
object that is erased derives from both of these types?
Your question is easier to understand if you rephrase it to be "is it legal to static_cast
from Holder_A_base_2 *
to Holder_B_base *
?" No, it isn't, and it won't compile.
Casting from Anchor *
to Holder_B_base *
will compile but will be Undefined Behavior unless the Anchor
object pointed to is the one that is part of Holder_B_base
.
If you need to cast from any Anchor *
to class that it is not part of, you can use dynamic_cast
. This allows cross casts.