Pointers and References¶
Understanding direct memory access is what makes C++ powerful.
Pointers¶
A pointer is a variable that stores the memory address of another variable.
Declaration and Usage¶
&(Address-of operator): Get the address of a variable.*(Dereference operator): Access the value at the address.
Null Pointer (nullptr)¶
Always initialize pointers. If you don't have a valid address, use nullptr.
Void Pointers (void*)¶
A generic pointer that can point to any type. You must cast it back to the correct type to use it.
References¶
A reference is an alias for an existing variable. It must be initialized upon declaration and cannot be changed to refer to another variable.
Pointers vs. References¶
| Feature | Pointer (*) |
Reference (&) |
|---|---|---|
| Nullability | Can be nullptr |
Must refer to a valid object |
| Reassignable | Can point to different objects | Bound for life |
| Initialization | Optional (but dangerous) | Required |
| Syntax | Explicit dereferencing (*ptr) |
Transparent usage (ref) |
| Arithmetic | Supported (ptr++) |
Not supported |
Guideline: Use references by default. Use pointers only when you need nullability or pointer arithmetic.
[!IMPORTANT] Modern C++ Note: Raw pointers (
*) should rarely be used for ownership (who deletes the memory). For managing resource lifetimes, always use Smart Pointers (std::unique_ptr,std::shared_ptr), which we will cover in Part 2. Raw pointers are fine for non-owning views.