Why use reference instead of pointers?

LeelaSwamy
LeelaSwamy used Ask the Experts™
on
Whatz the advantage of reference varaibles over pointers?
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Generally speaking, references are safer than pointers. Normally, when you have a reference, you can be sure that it actually points to a valid object, which surely isn't the case with pointers. Of course it's possible to create invalid references through the use of pointers, but that would sort of defeat the purpose of using references in the first place.

Also, syntactically it's simply nicer to define a function
void foo(mystruct &s)
then
void foo(mystruct *s)
because you can simply pass the object into the first version and you still have the efficiency of using a pointer. Also, as I said, it makes (more or less) sure the mystruct the foo function receives is actually valid. This can also be a disadvantage, though, when you'd like to pass null into the function for various reasons, but I guess in that case it would be better to overload the function anyway.

Clemens
In my opinion, references are just a lot cleaner than pointers.  You can use member functions with the . notation (rather than the -> notation, which intimidates some people).  You can use overloaded operators without having to dereference the member (i.e. out << or str += "stuff").  Things like assigning an int is also cleaner (x = 42 looks better than *x = 42).  People don't try to do things like pointer arithmetic with references, or accessing subscripts that don't exist.  Pointers are definitely useful, and I use them whenever things need highly optimized - where I might want to walk the memory myself, for instance, but references provide a cleaner syntax.  There are a couple of drawbacks (like the user of the function requiring the references doesn't know whether or not the object that the user's sending in will be modified or not), but most of these are easily overcome with good programming (like using const when it's not modified) and a little documentation.  Of course this is just my opinion.

Mike

Commented:
In some situations reference is an only way. For example, if you write:

cout << n << endl;

operator<< must return reference to the output stream, otherwise such string cannot be compiled. References are used in situations like this to create a temporary internal objects. You can find such samples, for example, in STL.
Learn SQL Server Core 2016

This course will introduce you to SQL Server Core 2016, as well as teach you about SSMS, data tools, installation, server configuration, using Management Studio, and writing and executing queries.

I would like to add one more important point.

When we use reference,the extra memory which is required for the pointer is saved. Reference don't use memory.
They r just like allias. If u use pointers,u have to allocate extra memory for them. U can save them by using references.

And i use references just because they look cleaner.  And also  u are quite safe since all the references are initialised. They is nothing like uninitialised pointer which are the most common problem encountered during debuging.
Commented:
C++ code is converted by C++ compiler to Assembly. In Assembly there are no references, only pointers. Reference is only C++ concept handled by compiler. I don't beleive there is extra memory in using pointers.

Passing parameter by reference is not readable in the caller code:

MyFunction(myObject);             // by value or by reference?

may be both of them:

void MyFunction(SomeObject& object);      // by reference
void MyFunction(SomeObject object);        // by value

By the way, in C# caller must use byref keyword passing parameter by reference, this makes a caller code more readable and clear.

Commented:
"references" are just slighty gussied up pointers.  There's a little more sophisticated  type-compatibility checking, so references are slightly less crash-producing than raw pointers.  You also can forget that they're actually pointers and use the less eye-jarring point.y syntax instead of point->y.

Unfortunately, since C++ still has to support pointers and pointer arithmetic, it's still all too easy to screw up references, but at least you have to work at it a bit more.

Author of the Year 2009

Commented:
>> Unfortunately, since C++ still has to support pointers and pointer arithmetic

"Unfortunately" C++ still doesn't pretend that a pointer to an object is the object itself.  

>>Whatz the advantage of reference varaibles over pointers?

There is none.  The only reason to use references is if you don't understand how to use pointers.

I hope that clears things up :)
-- Dan
It's wrong that there is no advantage. Operator overloading, for instance, can only be efficiently done with references.

Commented:
You HAVE to have pointers. HOW you gonna put anything on the heap?

References are not just another way to write pointers. There are several very important differences between references and pointers.

Operators act differently on reference variables than they do on pointers.  For instance;

int i,j,k;
int &ri, &rj, &rk;
int *pi, *pj, *pk;
// initialization code here
i = j - k;
ri = rj - rk;
pi = pj - pk;// error

The - operator means subtraction to integers, and also to integer references. The - operator means the difference (of type diff_t) between two pointers in pointed-to units (ints in this case). Arithmetic operators act on the referenced type when operands are references. This is important because it lets you write natural looking code for arithmetic on big types like matrices, tensors, etc.

Matrix<4,4> &A, &B, &C;
// initialization code here
A = B + C;

References have the quick argument passing semantics of pointers, but the lexical appearance of the referenced variables.

Another important property of references is that there is no null value like there is for pointers. Without doing dirty compiler tricks there is no way to convert 0 into a reference. When you declare a variable (particularly a function formal argument) reference, you are declaring a promist that the referenced object exists.

void f1(Foo& rf)
{
rf.operation(); }

void f2(Foo* pf)
{
Hmmm. Seem to have pushed the wrong button. To make my second point again,

void f1(Foo &rf)
{
    rf.operation();
}

void f2(Foo *pf)
{
    if (pf == 0)
        throw some_exception;
    pf->operation();
}

If I pass a pointer, the function is well advised to test it to ensure it's not nil. With references, the caller ensures the variable is well formed, so the function doesn't have to do it. Yes, the caller can act stupidly and just dereference a pointer to obtain an lvalue of the referenced-to type, which the compiler automatically converts to a reference. Then you'd have an unchecked reference, possibly to nil. But declaring a function with reference arguments means that the function isn't going to check for nil, so the caller mustn't do that. In a lot of situations the caller knows the pointer is not nil, or passes a variable of the referenced type. Using reference types allows you to save the cost of the test for nil, which can add up if a function is called a million times.

By the way, the comment by AlexFM is misleading. You don't have to pass references to make things like operator<< work. You do in iostreams because that is the way they are defined. But in general you could choose to return a value and still get an operator that let you say a << b << c << d... It wouldn't be very efficient unless the thing you were returning by value was as small as a register, but it would be legal.

Commented:
LeelaSwamy,
You have posted a total of five questions, and all five questions are open, and have not been awarded points.

You have 5 questions open in the C++ topic area, some of which are two months old.

Please award points for your previous questions and closed them.

Commented:
No comment has been added lately, so it's time to clean up this TA.
I will leave the following recommendation for this question in the Cleanup topic area:

Split: chofreither {http:#9238772} & mnashadka {http:#9238796} & shajithchandran {http:#9238955} & AlexFM {http:#9239018} & guntherothk {http:#9355826}

Please leave any comments here within the next seven days.
PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER!

Tinchos
EE Cleanup Volunteer

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial