5 - Pointers & References Flashcards
Diff btn references and pointers
- there are no null references
- all references require initialization when being created
- cannot be used to refer to a different object
Initializing a reference: a reference to a const can be initialized with a literal or temp value
const double &cd = 12.3; // No Error
double &cd = 12.3; // Error!
When a reference to const is initialized with a literal, the ref is set to refer to a temp location that is initialized with the literal. cd doesn’t ref to the literal 12.3 but to a temporary of type double that has been init to 12.3.
const double &cd = 12.3; // No Error template T add(const T &a, const T &b) { return a + b; } //… const string &greeting = add(string(“Hello”), string(“, World”)); // No Error!
Ref greeting refers to the unnamed temp string return value in the func add. When the temporary is used to initialize a reference to const, the temp will exist as long as the reference that it refers too. It is not deleted when the function add exits
Calling with mismatched types
void swapint(int & aInt, int & bInt){ int temp; temp = aInt; aInt = bInt; bInt = temp; } int main() { long a = 3, b = 5; swapint(a,b); }
Casted to two temporary ints to be passed in the constructor, so when you print after the swap, the values of a and b will still be the same. Solution: Labeling the method as explicit
const pointer and const data
left of * -> const data
right of * -> const pointer
Passing an array
void myFunction (int array[]) {…} void myFunction (int *array) {…}
Strings
c++ represents strings as arrays of characters that include ‘\0’ at the end. The value of the string is the address of the first character
Returning an object vs returning a reference
Returning an object invokes the copy cons., while returning a reference does not.