Savoga

Pointers And References


In C++, a reference is an alias to an existing variable.


void process(std::string& v){
    // v is an "alias"
    // No copy of the string is made when the function is called
    // Inside the function, using v is exactly the same as using food
    std::string v2 = v + " and beers";
    std::cout << v2 << std::endl;
};

int main() { 
    std::string food = "Pizza";
    process(food);
}

A pointer is a variable where the value is an address of what it is pointing to.


// The below prints:
// pork
// beef

int main() { 
    std::vector<std::string> food = {"pork", "beef"};
    std::string* ptr = &food[0];
    std::cout << *ptr << std::endl;
    ptr = &food[1];
    std::cout << *ptr << std::endl;
}