* BigBrian:
IMHO, that's silly ( saying that it's bad technique to throw from a
constructor ).
Yes.
What other mechanism is there to know if something goes
wrong with contructing an object?
An infinite number... ;-)
You can't return an error code from the constructor, all you can do is
throw an exception.
Nope.
class Silly
{
private:
bool iAmValid;
public:
Silly( int x, bool& ok ): iAmValid( x == 42 )
{
ok = iAmValid;
}
};
The reason why this _particular_ technique is bad is mainly that you risk
having invalid objects hanging around, so called ZOMBIE OBJECTS, which
necessitates much redundant checking of validity and leads to bugs.
Formally it's a kind of meta, second-level class invariant.
Worth noting: languages like Java and C# typically force you to have
zombie objects but in those languages the problem arises from the other end
of the object lifecycle, destruction. Because you don't have deterministic
destruction in those languages the programmer must call Dispose (or like)
methods explicitly, and the objects still exist afterwards. And so must
note for themselves that they're no longer valid, and so they're zombies
and can conceivably become zombies earlier on.
Also worth noting: handling of external resources in some cases require
zombie states. E.g., a file can become invalid at any time. An object
wrapping that file is then logically invalid for at least part of its
interface, a zombie object wrt. to the invalid parts of the interface.
Who said that [throwing an exception] is bad technique anyway?
Yes. Anyone worth listening to will tell the opposite. A clear but
limited discussion of why using exceptions in constructors, avoiding
zombie states, is given in Bjarne Stroustrup's TCPPPL appendix on
exception safety in the standard library, available as a PDF document
at <url:
http://www.research.att.com/~bs/3rd_safe0.html>.