Path: utzoo!utgpu!news-server.csri.toronto.edu!rpi!usc!rutgers!rochester!kodak!islsun!cok From: cok@islsun.Kodak.COM (David Cok) Newsgroups: comp.lang.c++ Subject: Re: typesafe downward casting Message-ID: <1991Mar30.161252.26129@kodak.kodak.com> Date: 30 Mar 91 16:12:52 GMT References: <17.UUL1.3#8618@softrue.UUCP> Sender: news@kodak.kodak.com Organization: Eastman Kodak Co., Rochester, NY Lines: 44 In article <17.UUL1.3#8618@softrue.UUCP> kearns@softrue.UUCP (Steven Kearns) writes: >There has been much discussion lately about adding stuff to C++ >so that people can assign a Base* to a Derived* without a cast. >People feel "guilty" when they use a cast, as if they are doing something >unsafe. > >If you look at things from a "program verification" viewpoint, the issue >becomes much clearer. A cast of (Base*) to Derived* is just a function >call that assumes that the Base* really points to a Derived*; if you >can prove to yourself (and God) that this is so, then using the cast >is perfectly safe, and you should not feel guilty. And if you can prove that global variables are used correctly, and goto's, and case statements or types, you should not feel guilty??? Some constructs are error-inviting -- cast is one of them -- and are best avoided. If you need to use them, you have to be very careful, but if a program has a lot of them bugs are likely. Current C++ can hardly be used for some kinds of things (at least the alternatives to casting are just as bad) without a lot of Base* to Derived* casts. It would add to the robustness and strong-typing nature of the language to have type-safe downcasts. > >If we added stuff to C++ to take care of this "problem", then we would >also have to add new types so that people do not call sqrt(x) when >x is a negative number, or so they do not call a/b when b is 0. > No, you don't have to. Every language is a trade-off between what is checked at compile-time, what is checked at run-time, and what is left to cause core dumps, often at places far from the original problem. People differ as to what should be in which category -- witness the whole static vs. dynamic typing debate. Numeric range problems have traditionally been left to either fault (at least at the location where they occur), or to cause a run-time exception. I think that a type-safe downcast is a legitimate thing to consider supporting at run-time. >-steve > >******************************************************** >* Steven Kearns ....uunet!softrue!kearns * >* Software Truth softrue!kearns@uunet.uu.net * >******************************************************** David R. Cok Eastman Kodak Company -- Imaging Science Lab cok@Kodak.COM