When to use Pointers in C/C++

A lot of people have asked me when you actually use pointers in C++ from day-to-day. I usually stare at them asking why they don’t use pointers everyday. Pointers are probably one of the biggest reasons you should even be using C or C++. There are several uses for pointers–too many to really go over. If you use C frequently, you are probably familiar with char*.

The golden reason to use pointers in my eye is controlling an object’s lifetime. Lets look at a scenario for an application I wrote a few months back. There was a contacts menu, and I had a class that represented a contact. It contained all the basic information you’d want a contact to have. Then I subclassed that and added more refined classes that represented personal contacts, business contacts, etc.

Here’s the thing. I had a vector that held all the contacts. How does one accomplish this? Set the template to hold pointers to Contact objects. This means, through the power of polymorphism, you can hold subclassed objects as well in the same vector. Now, this doesn’t really go with my golden rule for using pointers, however, you’ll see how I handle that.

When a user deletes a contact, you no longer want that object in existence (i.e. in memory). With a pointer, I can literally say “delete that object” and it will remove it from memory and I can handle everything else in the virtual destructor. Sure, you could just call a method to hide the contact, but when you are working with bigger objects you need to be thinking memory-conscious. One contact could be taking up 500KB to 1MB–possibly more when you throw in bigger images and more metadata. That may sound weak if you have 16GB of RAM sitting in your motherboard, but embedded apps have much lower amounts to work with.

Even still, pointers are dangerous if not used correctly. However, they are useful, and that is why the remain a coveted feature in C/C++ programming. Take the time to learn them if you are new. Just don’t worry when you get a message saying that you have corrupted the heap and everything crashes and burns–it just means you missed a delete.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s