+ 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?

8th Dec 2019, 3:58 PM
Иван
Иван - avatar
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 }
8th Dec 2019, 5:32 PM
Théophile
Théophile - avatar
+ 1
thank you Théophile
8th Dec 2019, 7:34 PM
Иван
Иван - avatar