Setup
There is starter code for this lab, but no unit tests. Instead, I’ve provided some main code that you can use to test your implementation. To get the starter code, run git pull and then cd copying.
The copying directory contains a complete implementation using dynamic arrays for the SetInt class from the ADT
lab. I’ve also added on functions to compute the intersection and the union of two sets.
Recognizing the problem
- Open up
main.cppand trace the code. With your knowledge of sets, what do you expect the output to be? - Compile and run
main. Does the output match your expectations? If not, what happens? - Run
valgrindon the program. Can you figure out which operation is causing the issue?
Fixing the problem
As you may have guessed from the topic of the lab, the problem is caused by the default shallow copy behaviour of the SetInt class. Since the class uses dynamic memory allocation, the rule of 3
applies.
It may be useful to check out the example from lecture
to see how the copy constructor and assignment operator were implemented for the StringStack class (now going in the correct order!).
Declare and implement a copy constructor for the
SetIntclass. Recall that a copy constructor should take aconstreference to anotherSetIntobject as its only parameter. The copy constructor should do the following:- Copy the primitive member variables from the other instance
- Allocate a new array of the same size as the other set
- Copy the elements from the other set into the new array
Compile and run
mainagain. Did anything change? What errors are still remaining?Declare and implement an overloaded assignment operator for the
SetIntclass. The assignment operator should take aconstreference to anotherSetIntobject as its only parameter and return a reference to the current object (this). In addition to the copy constructor steps, the assignment operator should first:- Check for self-assignment (in case someone says
some_set = some_set;) - Deallocate the current array before allocating a new one
- Check for self-assignment (in case someone says
Compile and run
mainagain. At this point, the remaining errors should be gone - if not, that means something isn’t quite right with your copy constructor or assignment operator.Finally, think about how you would thoroughly test this class. What edge cases should you consider? Try implementing some of these tests in
main.cppand making sure that your class behaves as expected, even if someone tries to do a weird thing like callingunion_on two empty sets.