Anonymous
Anonymous

Reputation: 9648

How to assign ifstream& return from method to variable?

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?

Upvotes: 1

Views: 1709

Answers (1)

Sarfaraz Nawaz
Sarfaraz Nawaz

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

Related Questions