I have a series of integers inside of a class. When the class is initialized, it requires the user make a call to another function to give value to the integers. If they don't call the function, the values are assigned 0.
That's nice and all but I have a boolean in there and I couldn't help but wonder how to return a bad boolean since the boolean isn't necessarily bad with either false or true.
A good way to fix this is to place the required function inside of the constructor to force the developer to call the function to give value to the integers and boolean. If the function fails to do this, you can set flags that tell the developer that it failed.
THE POINT: Let's say that fix isn't valid and it requires a call to a second function after the class is initialized. Those integers are nice and 0 but how would you tell the user that the boolean is bad (other than error flags set off in the in the constructor or default flag value)?
So I'm assuming then that 0 is not a valid integer value for your class?
I'll give two answers.
1. Use boost::tribool, which actually provides three boolean states: true, false, and indeterminate,
but you can rename the indeterminate state to whatever you like.
2. Avoid the problem and use RAII (Resource Acquisition Is Initialization). Essentially all this means is that you should write your class such that once the constructor completes execution,
the object is fully initialized and ready to use, not in some inbetween state where the user must then make further calls to completely intiailize it.
1 2 3 4 5 6
class Foo {
int x;
bool b;
public:
Foo( int x, bool b ): x( x ), b( b ) {}
};
I wasn't expecting so much of an answer >.>. Thanks again.
As for what I'll use, I'll probably go with boost::tribool. That sounds interesting indeed...
Normally, I WOULD use RAII and is what I do all the time. Unfortunately, I thought that perhaps it wasn't the best for my current situation. I'm going to experiment with it and see how it works out.
And I also like Disch's idea... But if I were to go with that method, I would go with error flags or some type of error checking.
@helios: Your enum isn't much different from boost's tribool except a little bit more... less problematic.