C already had mechanisms for allocating and deallocating memory (malloc and free). What are the C++ replacements for these, and what useful things do they do that malloc and free do not do?
Be able to write (with correct syntax) simple C++ code to
allocate and deallocate memory. For example, can you write the
C++ equivalents of the following statements?
float *fp = malloc(sizeof(float));
free(fp);
Be able to write (with correct syntax) simple C++ code to
allocate and deallocate memory for an array. For example, can you
write the C++ equivalents of the following statements?
float *fa = malloc(sizeof(float) * 10);
free(fa);
Be able to allocate and deallocate memory for a class instance in C++.
For example, can you complete the following statement so that bp points
to a dynamically allocated instance of class Bar? Can you write code to deallocate that instance?
Bar *bp = ________________ ;
References in C++ are a very useful variation on pointers.
Learn how to use them, including the rules for their syntax. For
example, can you rewrite the following code to use references instead
of pointers?
#include <iostream>
using namespace std;
void plus_5(int *ip) {
*ip = *ip + 5;
}
int main() {
int n = 3;
plus_5(&n);
cout << n << '\n';
}
It's legal for a base-class pointer to point to an object of a derived class. Is the same true for references? (I.e., can a base-class reference refer to an object of a derived class?)
What's wrong with the following function?
int& foo() {
int n;
n = 10 / 2;
return n;
}
If n were declared as static in the function above, would there still be a problem?
