-
Failing constructors
When you have a class the constructor should set all the private variables up but what happens if theres a problem and it can't? I am writing some code to do animations and I will load the details about an animation from a file. All the constructor will take is a filename and it will do the rest, but if the file doesn't exist or theres a problem with it I'm not sure how to handle it as constructors can't return anything back I don't think. Is there a nice way to do this at all? Thanks
-
well you can use a fail flag and put the class in a "zombie" state the way iostreams does or you can trow an exception.
-
For your situation, I would use the constructor to set all the variables to NULL and make a different function to open the file that can return an error value.
-
I would not make a separate init function. I would use RAII and initialize the object in the constructor and follow Darryl's suggestion of either setting a "bad" flag or throwing an exception. Throwing an exception is better for rare occurrences, so if the file should always be there (because it is put there by your program), then throw an exception if it won't load. If the file is placed there by the user or the user provides the path, these are often wrong, so a fail state might be more appropriate.