(ARTICLE) Prefer References Over Pointers

(ARTICLE) Prefer References Over Pointers

Even experienced C++ programmers who have prior experience with C 
tend to use pointers excessively whereas references may be a better 
choice. Pointers may result in bugs like the following:

Code:
bool isValid( const Date *pDate);

void f()
{
Date *p = new Date(); //default: current date

//...many lines of code

delete p; //p is now a “dangling pointer” 
bool valid = isValid(p); //oops! undefined behavior
p = NULL;
valid = isValid(p) //ops! null pointer dereferencing; 
//most likely will lead to 
a crash
}
The use of references eliminates the notorious bugs related to pointers: 
null pointer assignment and dangling pointer dereferencing, since a 
reference is always bound to a valid object:


Code:
bool isValid( const Date& date); //reference version

void f()
{
Date date; //default: current date

//...many lines of code

bool valid = isValid(date); //always safe
date += 100; //add 100 days
valid = isValid(date) //always safe 

}

[READ MORE ..]

COURTESY: www.go4expert.com

Google