1

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:

  1. Can I assign return value from open_file method to variable in main(), and if so how to do that?
  2. 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?
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
Anonymous
  • 9,366
  • 22
  • 83
  • 133
  • What you're trying to do, actually? I see, that you pass `val1` by reference, them return it and try to assign it to `val2`..? Also, what's the error description? – Kiril Kirov Nov 20 '11 at 14:50
  • Why return the pass the in reference parameter back out by reference anyways? If this was an operator, which can be easily chained, I could see it. Otherwise, any mutations of the in parameter from within the function can be observed outside anyways. – Michael Price Nov 20 '11 at 14:58
  • I try to return val1 back to val2 by reference. I come from C# background, need to understand how c++ copy work. – Anonymous Nov 20 '11 at 14:58
  • 1
    @Anonymous: You cannot "copy" streams, so trying to learn about copies in C++ with streams is a non-starter. – Lightness Races in Orbit Nov 20 '11 at 14:59

1 Answers1

3
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.

Community
  • 1
  • 1
Nawaz
  • 353,942
  • 115
  • 666
  • 851