struct A{}; struct B : A{}; int main() { A a; A& a_ref = a; static_cast<B>(a); // *1 static_cast<B&>(a_ref); // *2 return 0; } (*1) produces an error and i understand why. (*2) compiles fine, but why? And, as long as it compiles and suppose B contains some attributes, what if i cast a_ref to B& and then try to access the attributes? I think i will have an run-time error or something.
So, as i can see, there is a situation which leads to crash and there are no ways to avoid it, unlike with dynamic_cast where one can check the result of casting for null or put code in a try-catch region. How do i have to deal with such situation where i need to cast references and be sure that i really get the right references.
static_cast, there are no runtime exceptions on wrongly used statically casted results.static_castto downcast lvalues to references of derived classes, because there's no implicit cast for that way (as opposed to converting from a derived to a base class). You should only use it for that purpose if you know beforehand that it's safe (i.e. that the lvalue you're converting is of the derived type or derived).*2in isolation seems fine, since casting anA&to aB&would be valid in some situations. The compiler would have to do more sophisticated analysis to determine that it isn't actually valid in this case. This may be either too difficult or too slow to be practical.