Reputation: 9648
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:
Upvotes: 1
Views: 1709
Reputation: 361482
ifstream val2 = open_file(val1, "test.cpp");
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:
ifstream & val2 = open_file(val1, "test.cpp");
//val1 and val2 is same here, as val2 is just a reference to val1
But then, why would you even do that? You can simply write:
open_file(val1, "test.cpp");
//use val1 here - no need to define val2
Since the returned value is ignored, it is better if you make the return type void
. That is less confusing.
Upvotes: 3