Why do you put & after istream?

Hi im new to this language. I'm so confused about this.

When you make a fuction which reads a number to a variable, you put '&' after istream.

1
2
3
4
5
istream& read(istream& in)
{
  in >> num;
  return in;
}

Can anyone tell me what & means here in this code?
Last edited on
The & means your in argument is to be treated as a reference to an existing istream object, to avoid copying the entire istream you pass in to the function and all its data, which would be inefficient.
Last edited on
The & does not come after "istream", it comes before the name of the variable or function. The same with pointers. For instance:
char* a, b;
a is a pointer and b is not. To prevent this counter-intuitive looking code, always put the & or * closer to the variable name than to the type:
char *a, b;
This way it is easy and natural to say that a is a pointer and b is not.

Thus, your function can be written better as:
6
7
8
9
10
istream &read(istream &in)
{
  in >> num;
  return in;
}


@idratex: istream is not allowed to be copied, it would give you an error about not being able to access the copy constructor or operator=
Last edited on
L B wrote:
To prevent this counter-intuitive looking code, always put the & or * closer to the variable name than to the type

Another way is to never declare many variables in the same statement.
1
2
char* a;
char* b;

I prefer this way because pointer and reference is part of the type so it makes more sense to write it closer to the type name.
1
2
typedef char *char_ptr;
char_ptr a,b;
Muahahahahaha

wait...
Here's something: how do you think of this in your head?

MyClass * MyInstancePtr;

Would you think of it as MyInstancePtr being a pointer, and pointing to a MyClass?
MyClass *MyInstancePtr;

Or, would you think of it as MyInstancePtr being a variable of type (pointer to MyClass)?
MyClass* MyInstancePtr;

I think of it in the first way...
Last edited on
Topic archived. No new replies allowed.