I am just wondering if the following C++ code guaranteed to work:
struct B1 {
virtual void f() {};
};
struct B2 {
virtual void f2() {};
};
struct D:public B1,public B2 {
};
int main() {
D d;
B1 *b1=&d;
if (dynamic_cast<B2*>(b1)) {
B2* b2 = reinterpret_cast<B2*>(b1); //is this conversion valid?
};
return 1;
};
Of course, you would why do i need this? Because i want to replace this:
C::C(B1* b): member(dynamic_cast<B2*>(b)?dynamic_cast<B2*>(b)->m():b) {};
with better construction (by performance, to not check type safety twice):
C::C(B1* b): member(dynamic_cast<B2*>(b)?reinterpret_cast<B2*>(b)->m():b) {};
Thanks in advance!
No, that's definitely not valid. All you can do safely with reinterpret_cast is cast it back to the original type; anything else is implementation defined.