When declaring variables, the * symbol indicates a pointer type, while & indicates a reference type.
int x = 42;
int *ptr;
int &ref = x; // References must be initialized at declaration
ref = *ptr;
ptr = &ref;
int valueA = *ptr;
int valueB = ref;
The fundamantal distinction lies in their meaning: a pointer represents a memory address, whereas a reference represents the actual value stored at that address.
In the code above, ptr is a pointer variable holding an address, while ref is a reference that acts as an alias for the value. To retrieve the value from a pointer, the dereference operator * is required: *ptr yields the pointed-to value. To obtain the address of a reference, the address-of operator & is used: &ref returns the underlying address.
Beyond their declaration syntax, * dereferences a pointer to access its value, and & extracts the address from a value.
Since a pointer fundamentally stores an address, ptr can be assigned the address of a reference: ptr = &ref. Because a reference represents the value stored at an address, ref can be assigned the dereferenced value of a pointer: ref = *ptr.
int main()
{
int num = 100;
int &alias = num;
int *addressPtr = #
int newValue = 150;
std::cout << "Step1, num address:" << &num << "=alias points to:" << &alias
<< "=addressPtr value:" << addressPtr << "=dereferenced value:" << *addressPtr << std::endl;
std::cout << "addressPtr's own address:" << &addressPtr << std::endl;
alias = newValue;
std::cout << "Step2, num address:" << &num << "=alias points to:" << &alias
<< "=addressPtr value:" << addressPtr << "=dereferenced value:" << *addressPtr << std::endl;
std::cout << "addressPtr's own address:" << &addressPtr << std::endl;
}
Output:
Step1, num address:004FFE48=alias points to:004FFE48=addressPtr value:004FFE48=dereferenced value:100
addressPtr's own address:004FFE30
Step2, num address:004FFE48=alias points to:004FFE48=addressPtr value:004FFE48=dereferenced value:150
addressPtr's own address:004FFE30
This example reveals important behavioral differences between references and pointers. Both store addresses, but they operate differently at the memory level. A pointer is an independent variable allocated at its own memory location, containing the address it points to. A reference, however, is merely an alias—no new memory is allocated for it. The reference shares the exact same address as the original variable.
Modifying a reference directly changes the original variable's value. Since the underlying address remains unchanged, any pointer that references the same memory location will also reflect the updated value when dereferenced.