ihm
ihm

Reputation: 1863

why "istream& object" requires reference & and ifstream doesn't?

I understand no copy or assign for IO objects, so that we have to have reference sign & for istream/ostream objects. But why ifstream/ofstream or istringstream/ostringstream doesn't require a & to initialize an object? .

istream& input=cin;
ifstream infile;
infile("in");

istream needs a & and ifstream doesn't need a & to declare the variable.

Upvotes: 1

Views: 577

Answers (1)

GManNickG
GManNickG

Reputation: 503913

Those two aren't really comparable; one has an initializer and the other doesn't.

But std::istream input = cin doesn't work because streams are not copyable. If you tried to initialize infile with an existing ifstream, you'd get the same error. Obviously, a reference entails no copying and so it works, aliasing the existing value.

Going the opposite way, if you leave out the initializer, then you can't have a reference because a reference requires an initializer. Instead, your stream will just default construct.

Upvotes: 1

Related Questions