Raw Pointers
Rocket Run's collision code needs to change the health of whichever player the asteroid hit. It should not get a copy of that player; it needs a way to reach the real one. The oldest tool C++ has for that is the pointer: a variable that holds an address.
The rule
A pointer stores an address; * follows it, & takes it.
Every object lives somewhere in memory, and that place has an address.
int score = 10;
int* p = &score; // & takes the address of score
*p = 25; // * follows the address: score is now 25int* pdeclarespas a pointer to int.&scoregives the address ofscore.*pmeans "the object thatppoints at".
For objects with members, -> follows the pointer and picks a member in one step:
struct Player { int health = 100; };
Player hero;
Player* target = &hero;
target->health -= 30; // same as (*target).health -= 30A pointer that points at nothing should hold nullptr. Following a null pointer is undefined behaviour and usually crashes, so check before you use one:
if (target != nullptr) { // or simply: if (target)
target->health -= 30;
}Pointers called raw are these plain T* ones. They only point; they do not own or clean up anything. Later you will meet smart pointers that do.
The shortcut
Read a declaration from right to left, starting at the name.
Start at the name
pis ...
The trap is mixing up the two meanings of each symbol. In a declaration, * means "pointer to". In an expression, *p follows the pointer and &x takes an address.
Drills
Answer fast — trust the rule.
After int score = 10; int* p = &score; *p = 25;, what is score?
What value does p itself hold after int* p = &score;?
Which value should a pointer hold when it points at no object?
What does const int* p declare?
After int score = 10; int* a = &score; int* b = a; *b = 7;, what is *a?
Remember
- A pointer stores an address;
*follows it,&takes it. - Shortcut: read declarations from right to left.
- Trap: check for
nullptrbefore following a pointer.
