12.3 All together

When working with pointers and references, we can use both the symbols & and *. What they mean depends on the situation. Below are all the posibilities.

Suppose these variable exist:

 
int   j   = 43; 
int & ref = j ; 
int * ptr = &j;  

We can use these symbols

reference pointer



Declaration

int * i;




Declaration and Initialisation

int & i = j;

int * i = &j;




Initialisation

i = &j;







Assign value

i = 42;

*i = 42;




Assign value from variable

i = j;

*i = j;




Assign value from reference

i = ref;

*i = ref;




Assign value from pointer

i = *ptr;

*i = *ptr;







Assign address

i = &j;




Assign addres from reference

i = &ref;




Assign address from pointer

i = ptr;

References are a bit easier to use. But also less flexible. Sometimes you really need a pointer.

Exercise
  1. Create an application with 5 circles, spread out on the bottom of your screen. Create a memory container to hold these circles.
  2. When the mouse is on top of a circle, it should slowly move upwards.
  3. Create a function with a pointer to the highest circle as a result. Call this function in every update and keep the result in a pointer variable.
  4. Draw all circles on the screen. Before drawing a circle, compare its address with the address of the highest circle. When they are the same, draw the circle green, otherwise draw it red.