I have created a class and in the constructor I do something like:
MyClass(string file)
{
ifstream str;
str.open (file, ifstream::in);
// initialize class variables based on values from file
str.close();
}
How would I know though if there was an error while reading the file and the values were not initialized correctly? Is the above the wrong way to do it? How else could I proceed if I want my variables to be initialized from a file in the constructor?
Edit, to clarify: What I am asking is in a statement like:
MyClass myclass("path/to/my/file.txt");
how could I know that everything was initialized correctly?
One possibility is to use exceptions:
Then, if your constructor throws an exception, you know something didn’t work.
Another possibility is to detect the failure in the constructor and set a state variable which can be examined by the calling code.
Here are both solutions:
Assuming that
somefile.txtdoes not exist, that should print two lines of “oops”.Finally, a third possibility is to ensure that the constructor can never fail. In your case, you could provide default values in the
catchblock.