Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reason to Pass a Pointer by Reference in C++?

Under which circumstances would you want to use code of this nature in c++?

void foo(type *&in) {...}  void fii() {   type *choochoo;   ...   foo(choochoo); } 
like image 490
Matthew Hoggan Avatar asked Apr 20 '12 04:04

Matthew Hoggan


People also ask

Why would you want to pass a pointer by reference?

You would want to pass a pointer by reference if you have a need to modify the pointer rather than the object that the pointer is pointing to. This is similar to why double pointers are used; using a reference to a pointer is slightly safer than using pointers.

Is it better to pass by reference or pointer?

Difference Between Reference Variable and Pointer Variable: A reference is the same object, just with a different name and a reference must refer to an object. Since references can't be NULL, they are safer to use. A pointer can be re-assigned while a reference cannot, and must be assigned at initialization only.

Why do we pass pointers in C?

Example: Passing Pointer to a Function in C ProgrammingWhen we pass a pointer as an argument instead of a variable then the address of the variable is passed instead of the value. So any change made by the function using the pointer is permanently made at the address of passed variable.


1 Answers

You would want to pass a pointer by reference if you have a need to modify the pointer rather than the object that the pointer is pointing to.

This is similar to why double pointers are used; using a reference to a pointer is slightly safer than using pointers.

like image 176
David Z. Avatar answered Sep 18 '22 13:09

David Z.