Part 2 - References, Pointers, Arrays and Strings Flashcards
In C++ a variable of class type is associated with ________
a block of memory
If variables s1 and s2 are of type Student, the statement
s2 = s1;
will do what>
Make a copy of s1 and put it in the memory block associated with s2
Why would a loop like
for (i = 0; i<10; i++) {
Student s = a[i];
s. addMark(…);
s. updateAverage();
}
Not be suitable in C++?
What should be done instead?
s would make a copy of a[i];
Instead:
Student &s = a[i];
When declaring a reference variable what must be done?
i.e. what is not allowed?
Give it a value.
Student &s; would not be allowed
What is the default way of passing parameters in C++?
Call by value
Value is copied into local scope variable
What will
void swap(int &x, int &y) {
int temp = y;
y = x;
x = temp
}
do?
Swap the two integers passed in - references mean it is swapped outside the method also
When passing objects in C++ what type of calling is usually used? Why?
Call by reference
Because otherwise it would be pointlessly making a copy of the object
How should the function
void displayMarks(Student &s);
be defined if we want to guarantee s will not be modified?
void displayMarks (const Student &s);
When passing an array to a function what is actually passed?
The address of the start of the array
What will a return statement return if the return type is an object?
A copy of the object
Why should a reference to a local variable not be returned from a function?
What should be done instead?
Once control leaves the function the local variable will cease to exist
Instead return a copy
What do self referential classes need to use for the attributes of the same type?
Pointers
If a pointer p points to an object, how can the object it points to be accessed?
*p
Write a function to swap two integers using pointers
Show how it would be called
void swap(int* i1, int* i2) {
int t = *i1;
*i1 = *i2;
*i2 = t;
}
swap(&a, &b);
a->b is equal to what?
(*a).b
References are implicitly ___________ where as pointers must use the ________ operator
dereferenced
*
Write a function that takes a function pointer (to a function that takes and returns an int), an array and a length
void applyAll(int (*func)(int), int arr[], int len) {
for (int i = 0; i < len; i++) {
(*func)(arr[i]);
}
}
All data items on the stack must have a __________ size
fixed
When creating data items whose sizes are not known until runtime the
a) stack
b) heap
must be used
b) heap
If an array has been dynamically created like so:
int *anArray = new int[10];
How must it be deleted?
delete [] anArray;