I have a method name open_file declare as below.
ifstream& open_file(ifstream &in, const string &filename)
{
in.close();
in.clear();
in.open(filename.c_str());
return in;
}
I want to assign its return value to variable in main() method:
int main()
{
ifstream val1;
ifstream val2 = open_file(val1, "test.cpp");
return 0;
}
I can’t compile the code. My questions are:
- Can I assign return value from open_file method to variable in main(), and if so how to do that?
- If I can’t assign return value from open_file method to variable, what’s the difference if I change its return type to void?
This won’t compile because it attempts to make a copy of stream object, which is disabled by having made the copy-constructor
private(see this).Do this:
But then, why would you even do that? You can simply write:
Since the returned value is ignored, it is better if you make the return type
void. That is less confusing.