GeeksforGeeks » C/C++ Programming Questions

References vs Pointers

(6 posts)

Tags:

  1. geek
    guest
    Posted 1 year ago #

    Pros and cons of both?

  2. kartik
    Moderator
    Posted 1 year ago #

    If we talk in C++ context, then there are following pros and cons>

    Pointers vs References
    1 ) With pointers, we can get the memory address of a variable to which a pointer is pointing (Might be useful in embedded systems). Not possible with references.

    2) A pointers can have value as NULL to indicate that the pointer is not pointing to anything. Not inherent with references.

    3) Pointers can be changed to point to something else. This kind of property is useful when traversing a Linked List or other structures. Not inherent with references.

    4) Pointers are not safe. References are safer than pointers.

  3. kartik
    Moderator
    Posted 1 year ago #

    Things are different in Java. References are more powerful in Java.

  4. Venki
    Moderator
    Posted 1 year ago #

    References are necessary to achieve certain semantics of non-class types in global operator overloading. It is almost impossible to implement few operators overloading without references.

    An example,

    enum Events
    {
    Start = 0,
    Stop,
    Middle,
    EventsTotal
    };

    We want to overload ++ to fetch next Event, it can be done in the following ways, using references and pointers

    // Increment to next Event
    // This is the only way to increment in C++
    Events &operator++ (Events &m)
    {
    m = (Events)(m + 1);
    return m;
    }
    // It won't even compile, it redefines '*' semantics
    Events *operator++ (Events *m)
    {
    *m = (Events)(*m + 1);
    return m;
    }

    For more details see MSDN

    http://msdn.microsoft.com/en-us/library/4x88tzx0(VS.80).aspx

  5. kartik
    Moderator
    Posted 1 year ago #

    @venki: nice point. Copy constructor is also one thing where references are required.

  6. Venki
    Moderator
    Posted 1 year ago #

    @Karthik, Thank you. Small correction in your last point "Pointers are not safe. References are safer than pointers."

    References are safer than pointers, but not safest (fail proof). One can write cumbersome code using references. When references are passed/return to/from function things may go wrong. Also, a reference to pointer can guarantee to refer to pointer but can't ensure validity of pointer pointing to (usually this kind of code we can see in linked list manipulation, have look at Stanford library).

    But when carefully used, references do well and can result in better code. An example is STL swap() function to which you can't pass invalid addresses.


Reply

You must log in to post.

RSS feed for this topic