tags:

views:

217

answers:

3

What is the difference between passing-by-reference and using the C pointer notation?

void some_function(some_type& param)

and

void some_function(some_type *param)

Thanks

+4  A: 
  • You can't get a NULL reference: this alone gives you lots of safety
  • You can treat your reference as if it was an object: you can dereference it or whatever you need.

Basically you handle a safe pointer as if it was your own object.

Arkaitz Jimenez
you can easily get a null reference by dereferencing a null pointer.
Jherico
Thats being defensive or paranoic??
Arkaitz Jimenez
It's usually more of a mistake: your reference points to an object that has been destroyed or has never existed. Infamous example: `std::vector<int> myVec; myVec.front();`... how you regret then, that `std::vector<T>::front` does not throw out_of_range!
Matthieu M.
+4  A: 

Syntactic sugar.

When you pass a pointer to a variable in a subroutine call, the address of that variable is passed to the subroutine. To access the variable in the subroutine, the pointer has to be dereferenced.

When you pass a reference to a variable, the compiler takes care of obtaining the address of the variable when the variable is passed to the subroutine and dereferencing the variable in the subroutine.

David Harris
Marvelous! This helps a lot!
That's definitly NOT a syntactic sugar. There are differences, as you may see from the other answers.
SadSido
There are many subtle differences between the two as a reference is a alias. See below.
Martin York
A: 

A pointer can be repointed to a new object, but a reference cannot.

void MyFunction (MyType *myParameter)
{
    myParameter = new MyType ("BoogaBoogaBooga");
}

void main ()
{
    MyType *myArgument = new MyType ("WonkaWonkaWonka");
    MyType *myCopy = myArgument;

    MyFunction (myArgument);

    //myArgument is now pointing to the BoogaBoogaBooga object, but
    //myCopy is still pointing to the WonkaWonkaWonka object
}

Also, as others have already mentioned, a null pointer could be passed in, but a null reference could not be. Calling by reference provides nice syntactic sugar for accessing the provided object's members.

csj
sbk
I offer a complete and utter retraction. The imputation was totally without basis in fact, and was in no way fair comment, and was motivated purely by malice, and I deeply regret any distress that my comments may have caused you, or your family, and I hereby undertake not to repeat any such slander at any time in the future.- A Fish Called WandaOr should I simply say.... whoops. Is there a badge for first downvote received?
csj