# Key for Exam 1

• Problem 1

(a) Yes.

When a member variable of a class is a pointer to dynamic memory, the default constructor(shallow copy) won't work correctly. We must have a copy constructor. The copy constructor should allocates new memory for the new copy(deep copy), rather than just copying the pointers from one object to another.

/* The total is 10 pts. If the student answers yes, but fails to explain it correctly, only 5 pts were given. If the students answers no, but mentions the problem that the new copy's pointer will point to the old memory location without a copy constructor, only 8 pts were given. */

(b)

```node::node(const node& source)
{
myData = source.myData;
link = NULL;    /* base case */

}
```

/* This copy constructor is recursive. If the student writes link = source.link, only 20 pts were given. Only 2 students got this problem right, one used recursion, the other used iteration. */

(c)

```before call to foo,

b    ----------     c  ----------
|     |  |         |     |  |
|  20 | -|-------> | 30  | -|--> NULL
|     |  |         |     |  |
----------         ----------

after call to foo,

b    ----------     c   ----------
|     |  |         |     |  |
|  20 | -|-------> | 30  | -|--> NULL
|     |  |         |     |  |
----------         ----------
```

/* If you successfully did deep copying in Question b, you should have the right answer. If you did shallow copying in Question b, your data member myData in c will be changed to 10. In both cases, 25 pts were given. */

• Problem 2

(a)

```
void NameList::operator +=(const NameList & r){
for (int i = 0; i < r.mySize; i++)
myNames.push_back(r.myNames[i]);

mySize += r.mySize;
}
```

(b) Because the function that overloads += in the NameList class returns void and this means that L2 += L3 evaulates to nothing and therefore the "join" to L1 will not work.

(c)

```NameList NameList::operator +=(const NameList & r){
for (int i = 0; i < r.mySize; i++)
myNames.push_back(r.myNames[i]);

mySize += r.mySize;
return *this;
}
```

(d) Yes, the code in Part (c) works even if the argument to the function r is identical to the object onto which the function is being applied.

• Problem 3

(less important) saves time and space
(more important) sometimes a reference return type is required for some operations.
For example, apvector class has
itemType& operator [ ] ( int index );
so that we can do
L[3] = 5;
in this case we want to modify the original L[3], not just a copy of it.

• Problem 4

When the array is full, it is inefficient to increase the size of the array by one, every time the function is called. Typically, the size of the array is doubled, however, those who suggested more than one increment got full point.