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 as bar(&x)
(because it takes a pointer), or can call it with bar(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.
I also noticed if I use the 2nd method, I need to use -> as opposed to
. if I pass in a struct… why?
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).member
would mean the same thing as ptr.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 .
. So some_smart_ptr->get();
means “call the get()
function on the referand of the smart pointer”, whereas some_smart_ptr.get()
means “call the get()
function on the smart pointer”.
solved What does & in C++ function arguments list mean? [duplicate]