Based on the OP's comment (" I do not understand how casts could fail as mentioned by Scott."), the real question here is really something like: "how could a dynamic_cast
fail?"
The time it would fail is when the target type does not match the dynamic type of the object. For a simple example:
struct A {
virtual ~A() {}
};
class B : public A {};
int main() {
A *a = new A;
B *b = dynamic_cast<B *>(a); // should fail
if (b == NULL)
std::cout << "First cast failed.\n";
A *c = new B;
b = dynamic_cast<B *>(c); // should succeed
if (b == NULL)
std::cout << "Second cast failed.\n";
return 0;
}
Here although a
could point to an object of type B
, it actually does point to an object of type A
. When we try to do a dynamic_cast to get it to point to a B
, that fails. In the second attempt, we again have a pointer that not only could but does point to an object of type B
. Since it does, the dynamic_cast to B *
succeeds in this case.
The basic situation doesn't change (much) for the reference case, just a
, b
and c
become references instead of pointers, and we note the failure by catching an exception (which @ReedCopsey has already demonstrated well enough that I don't think I have anything new to add).