Possible Duplicate:
What are the differences between pointer variable and reference variable in C++?
What does a function prototype mean with an ampersand in it?
In my understanding,
void bar(int &x) { ... }
Seem to mean pass x by reference. But in C++, there are pointers etc already. So what difference is there to
void bar(int *x) { ... }
// then call by
bar(&x);
Apart from the fact that it’s longer… I also noticed if I use the 2nd method, I need to use -> as opposed to . if I pass in a struct… why?
The reason Stroustrup gives for introducing references to C++ is operator overloading.
http://www.stroustrup.com/bs_faq2.html#pointers-and-references
In your example function
bar, it is no big deal whether the user has to call it asbar(&x)(because it takes a pointer), or can call it withbar(x)(because it takes a reference). At least, C programmers think it isn’t.However, when operator overloading was added to C++, Stroustrup considered that using overloaded operators with pointers is very inelegant (“ugly” in his words).
References have some advantages in functionality over pointers, such as the fact that a temporary object can be bound to a const reference, but you can’t apply the
&operator to it. So a pass-by-const-reference function sometimes saves the caller a line of code (to create a variable) compared with its pass-by-pointer-to-const equivalent.For this reason, one possible convention is to accept a pointer when your function plans to store the address somewhere for future use after it returns, and a reference when it doesn’t. It doesn’t prevent all possible ways of creating a dangling pointer/reference, but it catches a big one. It does have unfortunate consequences when writing functional-style code, though, so it’s not for everyone.
It’s just the syntax inherited from C.
.to access a member of a struct,->to access a member via a pointer-to-struct. In C you can only use->with a pointer on the LHS, and you can never use.with a pointer on the LHS. So there’s no strict need for different symbols, it just helps make code more readable to have reminders. For example, if the same symbol.was used for both then(*ptr).memberwould mean the same thing asptr.member, which would probably be confusing.In C++ the difference becomes useful to the language. You can overload
operator->for a class type, for example smart pointers do. But class types can have members accessed with.. Sosome_smart_ptr->get();means “call theget()function on the referand of the smart pointer”, whereassome_smart_ptr.get()means “call theget()function on the smart pointer”.