Log in

View Full Version : C++: Pointers vs. References



Trinithis
09-05-2007, 06:02 AM
To make things clear, is the difference between pointers and references in C++ simply that:

references are just aliases for another variable, in that the original var and the ref have the same address

whereas pointers are data types that contain information about an address (where an object/primitive is located in memory), but multiple pointers to the same object do not necessarily have the same address for themselves?

(I come from a Java and JavaScript background.)

Twey
09-05-2007, 01:21 PM
Different references have different memory addresses too. The main difference between a pointer and a reference is that a reference can only ever point to the object you originally assign it. Pointers can be manipulated, but references can't. References are mainly a convenience: they simplify uses of pointers where you're never going to need to change the pointer itself. For example,
void addOne(int *n) {
*n = *n + 1;
}

// ...

int myint = 3;
addOne(&myint);... can more simply be written as:
void addOne(int &n) {
n = n + 1;
}

// ...

int myint = 3;
addOne(myint);You see how the use of a reference rather than a pointer makes everything pretty much transparent; the only difference from passing by value is the & symbol.