(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 */ if(source.link != NULL) link = new node(*(source.link)); /* inductive case */ }
(c)
before call to foo, b ---------- c ---------- | | | | | | | 20 | -|-------> | 30 | -|--> NULL | | | | | | ---------- ---------- after call to foo, b ---------- c ---------- | | | | | | | 20 | -|-------> | 30 | -|--> NULL | | | | | | ---------- ----------
(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.
(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.
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.