What is the requirement of references in C++?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Shilpa Sethi
    New Member
    • Aug 2010
    • 12

    #1

    What is the requirement of references in C++?

    Why do we need references in C++ when we can accomplish the same task with pointers?
    Putting it in other words:
    What are the advantages of using references over pointers?

    How actually is passing using references in C++ is faster and efficient than passing values using pointers?
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    References are passed as pointers. The compiler will de-reference the pointer for you.

    The advantage of references over pointers is that when you use pointers that you dereference yourself you will at some point screw up. The compiler never screws up.

    Second, studies have shown that member syntax is easy to use by programmers but they trip over pointer sytax:

    Easy:

    Code:
    int a = 10;
        fx(a);
    
    void fx(int& arg)
    {
       arg = 20;
    }
    Not so easy:

    Code:
    int a = 10;
        fx(&10);
    
    void fx(int* arg)
    {
        *arg = 20;
    }
    Third, a function argument that uses an object requires that a copy of the object by made. That is, the copy constructor must be called. To avoid the copy, you use pointers and pass the address of the object and this gets you the "not so easy" case. Using a reference avoids the copy and get you the "easy to use" case.

    Fourth, you use references as function arguments. Nowhere else are you to use references.

    Fifth, you use a reference argument if the function does not need to switch to another object. You can't change a reference to refer to another object. If your function needs to change the object, then you use a pointer.

    Sixth, review your code. If the function has a pointer argument and never changes the address in the pointer, then change the argument to a reference. You will find this eliminates 90% of the pointers in your code.

    Comment

    • whodgson
      Contributor
      • Jan 2007
      • 542

      #3
      Well there you go!.....and here I was, previously believing that a reference was simply another name for a declared variable full stop.

      Comment

      • donbock
        Recognized Expert Top Contributor
        • Mar 2008
        • 2427

        #4
        Not so easy indeed!
        Note the change to the argument when fx is called.
        Code:
        int a = 10; 
            fx(&a); 
          
        void fx(int* arg) 
        { 
            *arg = 20; 
        }

        Comment

        Working...