I am working with some low-level (by that I mean code that can't use C++ exceptions and/or the standard library) code that makes heavy use of classes.
Basically, every class contains a bool initialize();
method that is called right after instantiation to initialize all its components, underlying objects and such.
This is done because constructors in C++ can't return a value. Also every method that allocates memory, uses system API that may fail etc. must be checked for positive value.
However, this approach becomes very annoying after a while.
Consider the following code:
bool createHelloWorldString(String* string)
{
String str1;
if (!str1.initialize())
return false;
String str2;
if (!str2.initialize())
return false;
// Need to check return value as this method may fail because it dynamically allocates memory
if (!str1.set("Hello "))
return false;
if (!str2.set("world"))
return false;
if (!str1.append(&str2))
return false;
return string->append(&str1);
}
Note: This may not be the best example, but it clearly shows wheres the problem.
Are there any other ways to handle errors or am I stuck with this?