Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between references and pointers [duplicate]

Possible Duplicate:
What are the differences between pointer variable and reference variable in C++?

What does Class& mean in c++ and how is it different from Class*?

Class& foo;
Class* foo;
like image 524
user90450 Avatar asked Apr 14 '09 00:04

user90450


2 Answers

The & version represents a reference while the * version represents a pointer. The difference is far too big for a typical SO post. I suggest you start at the C++ FAQ lite

http://www.parashift.com/c++-faq-lite/references.html

I usually don't like to answer posts with a "you should use google" answer. However this is one topic that I highly advise you google. In particular google "c++ pointers vs. references". There is a wealth of information available on this topic and the discussions on those pages will trump anything we'll write here.

like image 87
JaredPar Avatar answered Oct 22 '22 22:10

JaredPar


The * is a pointer, the & is a reference. The difference between the two is that a pointer is an area of memory that must be dereferenced, eg. by means of the -> operator in order to be "seen" as a class instance. A reference is instead an "alias", just an alternative name for the same class instance. You don't need to use the -> operator with a reference. You use the dot operator.

Personally, I rarely used the references, mostly when I had a value object that I allocated on the stack. The new operator always returns a pointer, which you then have to dereference. Moreover, one of the most problematic issues of the references is that you cannot set them to NULL. In some cases, it is handy to have a function that accepts either an object pointer or NULL. If your function accepts a reference, you cannot pass a NULL (you could use the Null object pattern, however)

like image 43
Stefano Borini Avatar answered Oct 22 '22 23:10

Stefano Borini