+ 2
References & Pointer
When to go for referances and pointer as a paramter while writing any function ? What differences it makes in real time over pointer use?
1 Resposta
+ 1
References are often thought of as memory addresses. Pointers are also memory addresses; what can be done with a reference can also be done with a pointer.
The difference is that a reference always points to exactly one object, and in its existence it always points to exactly the same object. When a reference is created, it becomes one with one of the objects; it cannot be switched to another object. In contrast, a pointer can be switched to another, and even a pointer can be 0, meaning it can do so without pointing anywhere.
The reference points to a single object, the pointer can also point to an array of objects. This is why you need to be careful with pointers, because basically a pointer does not show how many elements it points to. Used correctly, this is what makes a function wait for an object to change or an array:
void fv(char& c); /* a number you would write into */
void fv(char* c); /* array of characters */
Another example:
Count function with pointers:
int s, m;
int a = 5, b = 9;
count(a, b, &s, &m);
void count(int one, int two, int *sum, int *multiplicative) {
*sum= one+two;
*multiplicative= one*two;
}
Count function with references:
int s, m;
int a = 5, b = 9;
count(a, b, s, m);
void count(int one, int two, int& sum, int& multiplicative) {
sum= one+two;
multiplicative= one*two;
}