Reference Variable


  • A reference is a variable name that is a duplicate of an existing variable. It provides a technique of creating more than one name to designate the same variable. The syntax of creating or declaring a reference is:
  • Data Type &ReferenceName = VariableName;
  • To declare a reference, type the variable's name preceded by the same type as the variable it is referring to.
  • Between the data type and the reference name, type the ampersand operator "&".
  • To specify what variable the reference is addressed to, use the assignment operator "=" followed by the name of the variable.
  • The referred to variable must exist already.
  • You cannot declare a reference as: int &Mine;
  • If you change the value of the variable, the compiler updates the value of the reference so that both variables would hold the same value. In the same way, you can modify the value of the reference, which would update the value of the referred to variable.
  • To access the reference, do not use the ampersand operator; just the name of the reference is sufficient to the compiler.
    Example

    Passing References to Objects

  • We have seen that when an object is passed as an argument to a function, a copy of that object is made.
  • When the function terminates, the copy's destructor is called. If for some reason you do not want the destructor function to be called, simply pass the object by reference.
  • When you pass by reference, no copy of the object is made.
  • This means that no object used as a parameter is destroyed when the function terminates, and the parameters destructor is not called.
    Example
  • Here is the output of this program: Constructing 1 -10 Destructing 1
  • As you can see, only one call is made to C's destructor function.
  • Had O been passed by value, a second object would have been created inside neg( ), and the destructor would have been called a second time when that object was destroyed at the time neg( ) terminated.
  • As the code inside neg( illustrates, when you access a member of a class through a reference, you use the dot operator.) The arrow operator is reserved for use with pointers only.
  • When passing parameters by reference, remember that changes to the object inside the function affect the calling object.
  • One other point: Passing all but the smallest objects by reference is faster than passing them by value.
  • Arguments are usually passed on the stack. Thus, large objects take a considerable number of CPU cycles to push onto and pop from the stack.


This Pointer << Previous

Next >> Polymorphism

Our aim is to provide information to the knowledge seekers.


comments powered by Disqus


Footer1