5 - Pointers & References Flashcards

1
Q

Diff btn references and pointers

A
  • there are no null references
  • all references require initialization when being created
  • cannot be used to refer to a different object
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Initializing a reference: a reference to a const can be initialized with a literal or temp value

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Calling with mismatched types

A
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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

const pointer and const data

A

left of * -> const data

right of * -> const pointer

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Passing an array

A
void myFunction (int array[]) {…}
void myFunction (int *array) {…}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Strings

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Returning an object vs returning a reference

A

Returning an object invokes the copy cons., while returning a reference does not.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly