Path: utzoo!utgpu!news-server.csri.toronto.edu!rpi!zaphod.mps.ohio-state.edu!samsung!uunet!taumet!steve From: steve@taumet.com (Stephen Clamage) Newsgroups: comp.lang.c++ Subject: Re: Constructors and Error Conditions Message-ID: <789@taumet.com> Date: 29 Jun 91 15:09:59 GMT References: <5032@gmdzi.gmd.de> Organization: Taumetric Corporation, San Diego Lines: 48 >Since Constructors do not return any value on completion how can I react >on error conditions while executing the Constructor i.e what to do if I want >to create an Integer in the range 34..59 via Construktor parameter and that >parameter is out of that range ? >One solution may be to introduce an additional out parameter reflecting >the end state of the execution; but this seems not very smart to me. The usual solution is to introduce a 'status' function which is tested before or after a use of an object, or after constructing it. A similar solution, where there are only two possible status cases, is to define a type conversion to, say, void*, which can be tested in a boolean expression. Examples: enum state { GOOD, OK, FAIL }; class c1 { state stat; public: c1(int); state status() { return stat; } }; f1(...) { c1 c(1); if( c.status() != FAIL ) ... else ... } class c2 { public: c2(int); operator void*() { return (all is ok) ? this : 0; } }; f2(...) { c2 c(1); if( c ) ... // c is automatically coverted to void* else ... } Once exceptions are widely available in implementations, they are the way to handle the problem. You define an exception for failure of a constructor, and raise the exception inside the constructor. This will transfer control to the exception handler, which might simply abort the program. -- Steve Clamage, TauMetric Corp, steve@taumet.com