6

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
    I doubt somebody is going to reproduce one of the 1000 tutorials and explanations that already exist here. Have a look at: http://www.parashift.com/c++-faq-lite/references.html – pmr Oct 30 '09 at 00:41

2 Answers2

7

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
  • 2,332
  • 1
  • 13
  • 25
6
  • 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
  • 22,500
  • 11
  • 75
  • 105
  • 6
    you can easily get a null reference by dereferencing a null pointer. – Jherico Oct 30 '09 at 00:47
  • Thats being defensive or paranoic?? – Arkaitz Jimenez Oct 30 '09 at 00:50
  • 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 myVec; myVec.front();`... how you regret then, that `std::vector::front` does not throw out_of_range! – Matthieu M. Oct 30 '09 at 07:19