I haven't read this thread word-for-word, so I may be simply repeating what someone else has said, but it never hurts to reiterate.
In C, you don't have references. You
just have pointers, so C code does use pointers as a way of passing arguments "by reference" so that you can change the values of the arguments in the function itself, as in the very common swap() example:
- Code: Select all
void swap(int* a, int* b) {
int temp = *a;
*a = *b;
*b = temp;
}
C++ introduced references, which do away with the need of having all the asterisks in code like this.
- Code: Select all
void swap(int& a, int& b) {
int temp = a;
a = b;
b = temp;
}
Much cleaner. So in C++, references and pointers now serve
two distinct purposes. You can use pointers the C way for passing arguments by reference, but that's doing it the C way, not the C++ way. There are many, many situations where using pointers is necessary, however. Pointers are how you manage values that are stored in the
heap, instead of the
stack. When you create an object in C++ (a regular old object, not a pointer), like so
- Code: Select all
MyObject object("hi");
it is allocated on the stack, and it is removed completely from memory when the block of code it was in ends (when it hits a "}"). Dynamically allocated values don't live by those rules. For example, making an object like this:
- Code: Select all
MyObject* object = new MyObject("hi");
Will allocate it on the heap (which is just a fancy word for how the runtime keeps track of the memory that your program owns). They will stay around as long as you want them to.
It's hard to describe how this is useful if you haven't encountered the need before, but perhaps the most trivial and powerful example is a linked list. Take a look at
Wikipedia's linked list article and notice that pointers play a core role in making them work.
Another example: C++'s vector STL data-type isn't a linked list, but an array of dynamically allocated memory. Arrays have a fixed size. When you pump more values into an STL vector than its array can hold, the STL dynamically allocates a new array, and copies all the values from the old array into the new one. The only way this dynamically allocated array can be kept track of and used is via a pointer to tell the STL where it is so that it can be manipulated.