References Versus Pointers
Table of Contents

Differences

Pointers References
you must use an explicit operator-the * operator-to dereference a pointer You don't use an operator to dereference a reference
Not constant by default constant by default
a pointer can point to many different objects during its lifetime , a reference can refer to only one object during its lifetime
A valid reference must refer to an object A pointer can be null
Use references when you can Use pointers when you have to (c++ FAQ)

you must use an explicit operator-the * operator-to dereference a pointer, but you don't use an operator to dereference a reference.

Examples

Example 1:

#include <iostream>
using namespace std;
 
/*
 * A pointer is a variable that holds the address of another variable.
 *
 * A reference is an alias to another variable.
 */
 
int main()
{
  int weight = 90;
  int *pWeight = &weight;
  int &rWeight = weight;
  cout << "Weight = " << weight << endl;
  cout << "Weight (pointer) = " << *pWeight << endl;
  cout << "Weight (reference) = " << rWeight << endl;
 
  int another_weight = 100;
  /*
   * The following line does not reassign rWeight.
   * It assigns a new value to the variable that rWeight references.
   */
  rWeight = another_weight;
  cout << "Weight (reference) = " << rWeight << endl;
 
  int third_weight = 120;
  /*
   * The following line changes pWeight only.
   */
  pWeight = &third_weight;
  cout << "Weight (pointer) = " << *pWeight << endl;
 
  return 0;
 
}
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-Share Alike 2.5 License.