Jun 132012
 

What is the difference between reference & pointers in C++? Is it safe to use pointers in places where we use reference & vice-versa?

Solution:

If we are from C background then we some times tend to use pointers and not references. It is harmful, because in C++ there are classes, objects, constructors (esp. default and copy constructors), overloaded assignment operator and they come into picture when we pass arguments to functions and assign one object to another.

Lets discuss few area you may want to keep in mind:

1. references are always initialized and cannot be null, pointers may be null

I cannot define a reference without telling what it refers to. For example the below definition is an error

    int & x = NULL;   // ERROR
    int * ptr = NULL; // OK

So, if I am receiving a reference in a function I don’t need to check it against NULL and can safely assume, that it must be getting some lvalue (else it will be compile time error). In case of pointers I cannot assume that, and hence have to put a check like this:

    void myFun(int * ptr)
    {
        if(ptr == NULL) 
        { 
            // take some action
        }
        // Rest of the function
    }

2. Pointers may be reassigned to refer to different objects

A pointer may point to any variable of its type and may change. But a reference always refers to the same object to which it is initialized.

    int a = 5;
    int b = 10;

    int *ptr = &a;	 // ptr points to a and *ptr = 5
    ptr = &b; 	// ptr points to b and *ptr=10

    int &ref = a; 	// ref is just another name for a. ref=5
    ref = b;	 // ref will NOT refer to b but value of a & ref will be changed to 10 (same as a=b)

Hence you should use them keeping this property in mind.

3. Copy constructor

The copy constructor only accepts reference and not pointer to object

4. Operator overloading

When we overload certain operators, the reference becomes the obvious choice. For example, Assignment operator returns a reference to the object to which the value is assigned. This is to make the assignment like below possible:

a = b = 5;

If a and b are int then it will be handled by the compiler, but if they are user defined types, and we are overloading the assignment operator, then that function should return a reference (and not pointer).

 Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

(required)

(required)