This code is invalid and does not compile:
struct A { int x; };
struct B : public A {};
void f( B** p ){
A** pa = p; // type mismatch
}
It looks innocent though, and it appears to work with reinterpret_cast. I understand that there are cases where this wouldn't be so simple, e.g. when multiple inheritance is involved, but in this particular case here there shouldn't be any problem, and the compiler should be able to figure this out. So why is this not allowed in C++? And is reinterpret_cast a good way around this limitation, considering exactly the types given above?
What might happen were it allowed:
struct A { int x; };
struct B : public A { int y; };
//...
B b;
B* pb = &b;
A** ppa = &pb;
A a;
*ppa = &a; // ppa points to pb, thus henceforth, pb == &a
pb->y = 100; // oops!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With