Main Content

References and Pointers in C++

Archive - Originally posted on "The Horse's Mouth" - 2006-07-10 08:17:32 - Graham Ellis

I always know that when I'm running a C Course, the concept of pointers will be one of the more difficult elements for some of the delegates to grasp. No big deal, I can explain them in a number of ways, provide examples from different angle, and we'll be over the hiccough in progress in not too long a time. Pointers provide an exceptionally powerful capability, but C's an old language now and they're not exactly newbie-friendly.

You have C's pointers available in C++, but you also have references ...
* A Pointer is a variable the contains the address of another variable.
* A Reference is an alternative name that's assigned to a variable.

Thus, when you use a pointer, you need to prefix it with a "*" to mean "contents of" and to set it, you need to prefix it with "&" to mean address off, and that's simply not necessary with a reference.

Here's a sample from our C++ Course that displays data from an array using both the pointer way and the reference way:


int weights[] = {96,98,100,99,98,95};
for (int k=0; k < 6 ; k++) {
int &rWeight = weights[k];
int *pWeight = &weights[k];
cout << "rWeight " << rWeight << endl;
cout << "*pWeight " << *pWeight << endl << endl;
}


Do be careful - if you assign something to an existing reference, you're changing the value of the variable that it's aliased to and you're not making the reference point at something else .... but if you assign something to an existing pointer, you're changing what it points to.