C++ Pointer Rundown

There are a few operators in C++ that mean different things depending on their context. Here’s a quick guide gathered from the Reference and Pointer tutorials found at www.w3schools.com:

// Create a variable
string food = “Pizza”;
cout << food << “\n”; // Pizza
cout << &food << “\n”; // memoryLocation1

// Used in a variable definition, “&” creates a reference to food (meal refers to the same “Pizza”)
string &meal = food;
cout << meal << “\n”; // Pizza
cout << &meal << “\n”; // memoryLocation1

// Create a copy of food (new pizza is also “Pizza”, but not the same pizza as food)
string newPizza = food;
cout << newPizza << “\n”; // Pizza
cout << &newPizza << “\n”; // memoryLocation2

// Used in front of an existing variable, “&” gets the address of the variable (a pointer stores an address as its value)
string* address = &newPizza;
cout << address << “\n”; // memoryLocation2

// Used in front of a var defined as a pointer, “*” dereferences that pointer
cout << *address << “\n”; // Pizza

// Changing the value of a pointer will change what’s stored there (“address” was storing the address of newPizza)
*address = “Burger”;
cout << *address << “\n”; // Burger
cout << newPizza << “\n”; // Burger