A question about fstream

What's the difference between:

 
  fstream file("File.txt", ios::out);

and

1
2
  fstream file;
  file.open("File.txt", ios::out);

Is this the same thing as:

 
  int var = 0;

and

1
2
  int var;
  var = 0;

Last edited on
Anyone?
Yeah it's quite similar, but there are differences too.

Between int var; and var = 0; the value of var is undefined so it's not safe using at that point. If there are no code in between it should do the exact same thing though.

fstream file; will call the default constructor, which will initializing all member variables, so nothing is undefined, but open the file in the constructor might be a little bit more efficient compared to having two calls (default constructor + open).

I think the first one in both of these cases are preferred mainly because you are setting the variables to the state that you want them to be in as soon as possible. If you have a lot of uninitialized/unused variables hanging around there is bigger chance you use them by mistake, at the wrong point in the code. It's better to narrow the scope of the variable as much as possible so that the variable only exist for as long as it's useful.
Last edited on
Just as I thought. Thanks.
Topic archived. No new replies allowed.