+ 1
What for do we use pointers and references(* and &) in C++?
How might it be helpful? What is the difference between them. What is better?
2 Respostas
+ 1
Let's take an example : a function that take as parameter an image object. Without using pointers, it creates a copy of the object (so of the image). Now, how big is an image? Answer : too much.
Using pointer, you only give the address where the image object is stored. Then, instead of copying millions of bytes, you only copy 4bytes.
There is now a difference between pointers and references. They behave approximtibely the same way in our example, at the difference that passing by reference will create an 'alias' of the variable where our image is stored (that means that two différents name refer to the same variable).
The example :
void dosomething(image *iptr) {}
int main() {
image i;
dosomething(&i);
} // by pointer : iptr holds the address of variable i
void dosomething(image& im) {}
int main() {
image i;
dosomething(i); // here, i and im will be the same name for the same variable
}
+ 1
thank you Théophile