Tuesday, November 9, 2010

Pointers in C++

The pointers are very naughty in C++.
They always bias you as the programming language does not take care of pointers afters it is used by the programmer. It is completely left to the user how to handle the pointers. Since pointer is such a powerful feature that developers are always tempted to use it and they make their life miserable in most of the cases. It is just like credit card, if you use it diligently you are always in profit, but a small carelessness can put you in lot of trouble.
So the first approach should be whether the kind of job you want to do is possible by using the reference? If at all you use pointer, refer the object(memory) pointed by pointer, i.e., (*p) NOT (p->) . This is good practise to use pointer this way since whenever the object goes out of scope, memory for this object will be  erased.
Also after pointer is used, make it to NULL so that it will not further point to the address it was pointing to since you can't delete the pointer, it is an auto variable. But the memory pointed by pointer can be erased if the memory is allocated in heap area. A single pointer can point to any memory segment, it is a variable. But the reference is constant since it is only allowed to refer the object it is associated, it can't be associated with other object, it is like marry once and live together for ever. Try to allocate memory dynamically by pointers as we need not overburden  the executable by allocating all the memory , we will create memory in execution time only on demand.