C++ Programming Concepts

Learn C++ and get Object Oriented

C++ Programming Concepts made easy...
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

C++ Programming Concepts - Pointers vs. References

References vs. Pointers


References and Pointers in C++ have some interesting relations and subtle differences too.

Syntax 

int i ;
int *p = &i ;
// p is pointer, which is currently pointing to variable i

int &j = i ; // j is reference to variable i, and will be for lifetime.

Notice the use of & symbol in both the statement. In the first statement it represents the Address of operator, which retrieves the address of its operand i. In the second statement however, it is representing the reference operator which merely indicates that j is a reference of integer type.


&OPERAND --> Address Of operator, OPERAND is any variable - which has an address
TYPE& --> The Reference operator, TYPE is the data type of reference which is to be created.

Pointers are Variables, References are not

Pointers are variables - they can point to one variable, we can do some modification to the value of that variable using the pointer, and then the pointer can start pointing to another variable. It will store the address of some other memory location.However, References are not variable - once initialized with a variable, they refer to the same variable in their lifetime. After all, one can't assign a nick name to another person.

References are internally stored as pointers, we can think of them as constant pointers pointing to the same memory location always.

Initialization with NULL

A pointer can be initialized with or assigned a NULL value, which means that currently it is not pointing to any memory location. This is a perfectly valid state for the pointer. However, with References, this is not the case. A reference can't be initialized with or assigned a NULL value, it  has to be assigned to a variable.

Dangling Pointers and References

Both pointers and references can become dangling, which is an invalid state - for which the behavior is undefined.

Dangling Pointer

int *p ;
p = new int ;
delete p ; // p is dangling, till we assign it a new valid memory location.

Dangling Reference

// Code Snippet
int &funcRetRef ( ) ;
{
      int l ; return ( l ) ;
}

int main ( )
{
    int &k = funcRetRef ( ) ;
    ...
}


The funcRetRef ( ) has a return type of int&, which means that it is supposed to return a reference. But it does not return a valid reference. It returns a reference to an automatic local variable l which goes out of scope as soon as the function returns. Now, k contains an invalid reference, and we can't do anything to correct it. If you try to dereference k, you generally will get a segmentation fault, but the behavior is undefined.

Thus, Never return a reference or pointer to local memory.