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.