1

If an object is passed by value,then the value is copied to the object with the name of the parameter.Why should a reference be passed instead, when the type of an object is any of the : ifstream , ofstream , istream , ostream?

unsigned int number_of_lines(ifstream file) {

    string line;

    unsigned int lines=0;

    while(getline(file,line))
        ++lines;

    return lines;

}

In the code above, if the interface changes to:

unsigned int number_of_lines(ifstream& file)

Everything runs fine. Why is it obligatory to pass a reference?

Thanks!

Lukas-T
  • 11,133
  • 3
  • 20
  • 30
zach
  • 95
  • 1
  • 7
  • Does this answer your question? [C++ copy a stream object](https://stackoverflow.com/questions/7903903/c-copy-a-stream-object) – cigien Jun 09 '20 at 18:41

2 Answers2

4

Because otherwise you'd be copying it, and you cannot copy a stream.

A stream is a flow of data (not a container!). It makes no sense to try to copy that.

Asteroids With Wings
  • 17,071
  • 2
  • 21
  • 35
1

Those specific class types have disabled their copy constructors and copy assignment operators, preventing instances of them from being copyable at all. This is because their content is not designed to be copied.

That means they cannot be passed around by value, they can only be passed around by reference/pointer instead.

Besides, even if it were allowed, you wouldn't want to pass them by value anyway. Imagine what would happen if you tried to pass an ifstream object to a function that takes an istream by value - the ifstream would be sliced!

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770