A few days ago a friend of mine has questioned me as to why C++ does not uses pointers everywhere.

A pointer is not the safest thing to use

The first important thing to note is that a pointer is nothing more than a number -- an almost arbitrary number. This is a number that tells at which memory address a given object may start at. The word "may" is the key here: this object might not exist or the memory might not exist.

That's when things start to get ugly. If you are lucky, your code will just crash and a smile will pop: ha! theres something wrong at this pointer. However, that's not always true and sometimes the memory might be completely valid, but it points to something else entirely different and, when you change anything that was supposed to be stored inside the object, you are corrupting the application memory -- at this point, you are probably screwed. You application might behave weirdly and you will have a very hard time discovery why.

Any modern operating system does not gives application access to the physical RAM, instead it gives every application it's own virtual memory space. Because most operating systems allocate memory on demand, if you did not ask for the memory, it will probably not be available to you and will crash you application.

A pointer is not the fastest thing to use

Using a pointer is not as fast as using memory inside processor registers -- a register is a special kind of memory used by the processor. The processor will know what the registers are and fetch them very fast. Even better: the compiler can do some magic (it's not really that magic to be honest) and group them as close as possible to make it even faster. This is when a pointer can slow the application a lot. When the processor sees a pointer it has to dereference it -- this is a pretty nice word to say it will load the memory at that address.

At this point, the processor has to stop what it is doing, go all the way to the RAM memory, load, wait until the data arrives and then proceed. If the memory is not valid, the processor has to throw a trap signal that will crash the application.


I like to avoid pointers whenever possible. I mean, I don't think pointers are evil nor anything like that, but I believe it opens a whole highway of possible mistakes that you can avoid by using references or passing by values. Here's a general rule of thumb:

Yes No
Is your class is polymorphic? Reference, pointer only if nullable Value
Can your class be null? Pointer Reference