Passing by Reference

I wrote this function:

1
2
3
4
5
ostream& operator<<(ostream& out, LoginData& a)
{
	out << a.getLogin();
	return out;
}


and I originally wrote the first line of the function as
out << a->getLogin();

because I thought I was passing a pointer to a LoginData object. My compiler told me that I was passing a class and that I should use "." instead of "->" so I changed it and it compiles fine and seems to work correctly. So I then tested what would happen if I wrote ostream& operator<<(ostream& out, LoginData a) and it compiles and seems to work the same so now I am extremely confused about what I am doing and why both LoginData and LoginData& compile and work.
A reference is an alias for an object. If you don't pass by reference (that is, by value), a copy of the object you're passing is made.
But when I pass by reference, aren't I passing a pointer to the object instead of the object itself?
Sort of. It's like a pointer that is always dereferenced. As Athar said, if you don't pass a reference, a separate copy of the object is made for the function to use.
passing by reference allows you to access the data as if it were by value, even though behind the scenes the compiler may be passing a pointer rather than the actual value.

Topic archived. No new replies allowed.