Hi Doug!
See my comment, inline below:
On Friday, July 17, 2015 at 11:45:32 AM UTC-4, Doug Mika wrote:
> On Thursday, July 16, 2015 at 9:03:00 PM UTC-5, Doug Mika wrote:
> > Why is the following a compile time error and not a bad_cast exception:
> > ...
>
> So in the example that compiles, with ampersands, (I include the example again below) why doesn't it simply return rd=nullptr, why does it throw an exception.
Because you are casting to a reference, not a pointer,
so it can't return a nullptr.
> My question I guess is, when does dynamic cast throw an exception and when does it return nullptr?
The short answer is because that's how dynamic_cast is
designed to work. But the reason is that references can't
be nullptrs so there is no "singular value" for the reference
version of dynamic_cast to return to signal the "bad cast"
error condition. Hence it is designed to throw an exception.
> // bad_cast example
> #include <iostream> // std::cout
> #include <typeinfo> // std::bad_cast
>
> class Base {virtual void member(){}};
> class Derived : Base {};
>
> int main () {
> try
> {
> Base b;
> Derived& rd = dynamic_cast<Derived&>(b);
rd is a reference, so can't be a nullptr. The
dynamic_cast<SomeType&> returns a reference type,
and can't return a nullptr (because nullptr is
a pointer type, not a reference type).
> }
...
Good luck.
K. Frank