Reference or Pointer?
References and pointers both let you work with a variable from somewhere else, such as from a function. But they differ in a few ways:
| Reference | Pointer | |
|---|---|---|
| Creating | int& r = x; | int* p = &x; |
| Value | r, like an ordinary variable | *p |
| Function call | addPoint(score) | addPoint(&score) |
| "Nothing" | not possible, a reference always belongs to a variable | nullptr, check it before use |
| Another variable | not possible, a reference always belongs to the same one | p = &y; |
So when should you use which? Prefer references:
- The function should change a variable or a vector: a reference,
int& score,std::vector<int>& scores. - The function only reads a vector or text: a const reference,
const std::vector<int>& numbers,const std::string& name. - Use a pointer only when you need "nothing" (
nullptr) or to redirect it to another variable, or when a library you use requires it.
References are simpler and safer: you don't write asterisks, you can't forget the & in a call, and a reference can't be nullptr, so you don't have to check it. But pointers stay important in C++. You will need them in more advanced topics, for example when a program asks for new memory while it runs, or when you build your own data structures.
Instructions
- 1
The program prints
Hi!Hi!Hi!, but both functions use pointers for no good reason. Rewrite the functionaddExclamationso that it takes a referencestd::string&instead of a pointer. You then won't need*inside the function or&in the call. - 2
Rewrite the function
repeatthe same way. The program still printsHi!Hi!Hi!. - 3
Below the function
repeat, write a functionwrapwith two parameters of typestd::string: thetext, which the function changes, and theborder, which it only reads. Use the rules above to choose how to pass them. The function adds the border to the beginning and to the end of the text. Before the print line, callwrap(greeting, "**"). The program prints**Hi!Hi!Hi!**. If you passed the border by reference withoutconst, compiling would end with the errorno matching function for call to 'wrap': text in quotes isn't a variable, so a plain reference doesn't accept it.