Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference between a pointer and reference parameter?

Are these the same:

int foo(bar* p) {   return p->someInt(); } 

and

int foo(bar& r) {   return r.someInt(); } 

Ignore the null pointer potential. Are these two functions functionally identical no matter if someInt() is virtual or if they are passed a bar or a subclass of bar?

Does this slice anything:

bar& ref = *ptr_to_bar; 
like image 527
criddell Avatar asked Mar 06 '09 22:03

criddell


People also ask

What is the difference between reference variable and pointer variable explain with example?

Pointers: A pointer is a variable that holds the memory address of another variable. A pointer needs to be dereferenced with the * operator to access the memory location it points to. References: A reference variable is an alias, that is, another name for an already existing variable.

What are the most significant differences between references and pointers?

Appearances aside, const pointers differ from references in one subtle but significant way. A valid reference must refer to an object; a pointer need not. A pointer, even a const pointer, can have a null value. A null pointer doesn't point to anything.

What is the difference between a pointer value and a pointer reference?

Pointers are variables; they contain the address of some other variable, or can be null. The important thing is that a pointer has a value, while a reference only has a variable that it is referencing.

What's the difference between pass by reference and pointers?

The difference between pass-by-reference and pass-by-pointer is that pointers can be NULL or reassigned whereas references cannot. Use pass-by-pointer if NULL is a valid parameter value or if you want to reassign the pointer. Otherwise, use constant or non-constant references to pass arguments.


1 Answers

C++ references are intentionally not specified in the standard to be implemented using pointers. A reference is more like a "synonym" to a variable than a pointer to it. This semantics opens some possible optimizations for the compiler when it's possible to realize that a pointer would be an overkill in some situations.

A few more differences:

  • You can't assign NULL to a reference. This is a crucial difference and the main reason you'd prefer one over the other.
  • When you take the address of a pointer, you get the address of the pointer variable. When you take the address of a reference, you get the address of the variable being referred to.
  • You can't reassign a reference. Once it is initialized it points to the same object for its entire life.
like image 177
shoosh Avatar answered Oct 15 '22 14:10

shoosh