1. Technology

Know the difference between a Reference and a Pointer in C++?

By August 10, 2006

Follow me on:

A reference can be thought of as a special type of pointer with certain restrictions. Once a reference points to a variable it is stuck. It cannot be reassigned. Personally I've found references most useful for simplifying access to variables when passed in as parameters to a function. Although a reference can only be attached once, because it belongs to the function, it can be assigned each time the function is called.

function example(int & value) {
// do something
}

for (i=0;i< 10;i++)
  {
    example( fred[i]);
  }

Also important is the fact that each element of fred is being passed by reference. This means that value (within the example() function) is directly accessing the array fred[] and not a copy of each element. With small size variables like ints this is less important but if fred was an array of a very large object, then passing by value would need to copy each element which is slow. So passing by reference is a lot more efficient. It's just like the pascal 'var' parameter.

Comments
November 14, 2009 at 2:56 pm
(1) IntGk says:

It is true that the in this code passing reference of fred[i] is faster then passing values. But what is important is the difference between passing by value and passing by reference.
if you do not want the values of fred to be changed inside exapmle() you are bound to pass them by values. there you can not use reference or pointer though it makes the programm faster.beware.

November 17, 2009 at 5:39 pm
(2) hakayashii says:

If you don’t want to change the value inside the function you can use const refernces and pointers. Example:
int example( const& LargeObject value ){…}.

Now you can be sure that value wouldn’t change and the performance is the same as whitout const.

November 23, 2009 at 5:33 pm
(3) hakayashii says:

I have to correct my self, it should be ‘const LargeObject&’

November 19, 2010 at 4:24 am
(4) Monster says:

Well corrected, and good point. Also note it doesn’t need to be a “large” object that is passed by reference. I usually pass by const ref to functions rather than by value. I feel it makes the code clearer for the reader.

Leave a Comment

Line and paragraph breaks are automatic. Some HTML allowed: <a href="" title="">, <b>, <i>, <strike>

©2014 About.com. All rights reserved.