[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: dynamic vs. static typing

Eli Collins <eli@cs.wisc.edu> writes:
> On Mon, 24 Nov 2003, Ken Shan wrote:
> > On 2003-11-24T12:14:20-0800, Steve Dekorte wrote:
> > > On Nov 24, 2003, at 11:33 AM, Ken Shan wrote:
> > > >Maybe -your- type system wouldn't allow it, but mine does:
> > > >  ...
> > > >See also dynamic_cast in C++.
> > > Is this a runtime cast check? If so, then don't we end up with
> > > potential runtime errors related to types? (which is what the typing
> > > system exists to avoid)
> >
> > No.
> To clarify, the dynamic_cast operator is a run time check, you do not get
> a run time error related to the type if the cast is illegal but a null
> pointer is returned (which you of course must check to avoid an error).
> Relevant pages are 407-409 in Stroustrup 3rd edition:
> "The purpose of dynamic_cast is to deal with the case in which the
> correctness of the conversion cannot be determined by the compiler."

In fact, dynamic_cast can generate a bad_cast exception if you use it
to cast a reference, rather than a pointer.  (See page 410 of
Stroustrup, actually.)

So while
Foo *x = dynamic_cast<Foo *>(bar);
will set x to Null if bar is not a pointer to a Foo, 
Foo &x = dynamic_cast<Foo &>(bar)
will throw a bad_cast exception if bar is not a Foo.