Reference Vs Pointer
Reference
Reference is like other languages like Python or Java pass by reference. In CPP we can create a reference by:
int originalValue = 999;
int& reference { originalValue } // direct assignment
cout << reference << endl; // 999
Now you can reassign the originalValue
with this reference
reference = 90;
cout << originalValue << endl; // 90
Reference will have the same memory address as the original object
cout << &reference << " = " << &originalValue;
Note: you cannot create a reference and assign later, for example:
int originalValue = 999;
int& reference;
...
reference = originalValue // CANNOT DO THIS
Reference is meant to assign at the point of creation
Pointer
Pointer, we can assign and reassign, pointer can be reuse and re-point
int *ptr { &originalValue }
*ptr = 5;
cout << orginalValue << endl; // 5
Pointer has different memory address comparing to the originalValue
cout << &ptr << " != " << &originalValue;
To refer to the memory address of originalValue
, we need to de-reference
&*ptr // equivalent to &originalValue
Pointer can be reused for different object and reuse
*ptr = otherInteger;