I'm new to C++ so my opinion is not worth all that much; but I've encountered at least a couple of different approaches.
In one library that I was using recently, every constructor has an int&
argument that returns the status of construction; the documentation for this library states that it will invoke undefined behaviour if the construction result is invalid. This approach makes it the caller's responsibility to ensure not to use the invalid class.
TheClass::TheClass(int &result)
{
result = -1; // or some error value
// do lots of initialisation
result = 0; // success
}
Another one that I saw had an is_valid()
method. If the construction failed, a boolean member variable was set to false and was returned from this is_valid()
method (this method also checked a couple of other things as well). I managed to see the source for this and found each member function starting out with an if(is_valid())
statement. I can't say I'm a fan of this approach.
TheClass::TheClass() : m_valid(false)
{
// do the initialisation
if (everything_ok)
m_valid = true;
}
void TheClass::method()
{
if (!is_valid()) return;
// do some work
}
I've read recently however that exceptions aren't as slow and kludgy as they used to be, and it is possible to implement them elegantly. Google may prohibit them for whatever reason, but they're still part of the C++ language. You might as well work with the tools you're given than to build a house with just a screwdriver.