Can anyone tell me why this doesn't compile:
struct A { }; struct B : public A { }; int main() { B b; A* a = &b; B* &b1 = static_cast<B*&>(a); return 0; } Now, if you replace the static cast with:
B* b1 = static_cast<B*>(a); then it does compile.
Edit: It is obvious that the compiler treats A* and B* as independent types, otherwise this would work. The question is more about why is that desirable?
ais not a reference to pointers its a pointer.B*&is a reference to a pointer toB.dynamic_castforces the compiler to embed runtime type information into that class hierarchy. Combine this with the relatively slow operation ofdynamic_castand it's a solution which you don't want to use unless it's necessary.dynamic_castwould not be legal here.