Reference

Reference :

  • When a variable is declared as reference, it becomes an alternative name for an existing variable. A variable can be declared as reference by putting ‘&’ in the declaration.
  • It is another name or label for the same memory location.
  • They are just like pointers but should not be confused with pointers.

Following are the properties references have but pointers don’t have :

  • It must be initialized when it is created.
  • Once a reference is initialized to an object, it cannot be changed to refer to another object.
  • There cannot be NULL references.
  • References are safer and easier to use
  • Since references must be initialized, wild references like wild pointers are unlikely to exist. It is still possible to have references that don’t refer to a valid location.
  • References don’t need de-referencing operator to access the value. They can be used like normal variables. ‘&’ operator is needed only at the time of declaration. Also, members of an object reference can be accessed with dot operator (‘.’), unlike pointers where arrow operator (->) is needed to access members.
Following examples illustrates all the properties of references :

OUTPUT :

Name=Arjun  Roll :121

Leave a Reply

Your email address will not be published. Required fields are marked *