Lab 22: Copying

Apr 4, 2024  β”‚  m. Apr 3, 2024 by Charlotte Curtis

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

  1. Open up main.cpp and trace the code. With your knowledge of sets, what do you expect the output to be?
  2. Compile and run main. Does the output match your expectations? If not, what happens?
  3. Run valgrind on 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!).

  1. Declare and implement a copy constructor for the SetInt class. Recall that a copy constructor should take a const reference to another SetInt object 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
  2. Compile and run main again. Did anything change? What errors are still remaining?

  3. Declare and implement an overloaded assignment operator for the SetInt class. The assignment operator should take a const reference to another SetInt object 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
  4. Compile and run main again. 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.

  5. Finally, think about how you would thoroughly test this class. What edge cases should you consider? Try implementing some of these tests in main.cpp and making sure that your class behaves as expected, even if someone tries to do a weird thing like calling union_ on two empty sets.



Previous: Lab 21: Recursion