CS 2005, B Term 1999
Techniques of Programming
Lab 2 (Nov. 10)
The objective of this lab session is to provide additional practice
with classes that use dynamic memory. In particular, you will see
what can go wrong when a copy constructor and overloaded assignment
operator are not provided for a dynamic class, and you will implement
these crucial member functions for a dynamic class that shares some
features of the DPoly class used for HW2. The insight gained through
this process should also be helpful for Test1.
- Sign in with the TA. You should both print your name
and sign the sheet.
- Listen to the TA's mini-lecture.
- Log onto your CCC Unix account and change the directory
to /cs/cs2005/samples/lab2/. That directory contains the
following files for a dynamic class named DynStuff:
- Specification file dynstuff.h
- Implementation file dynstuff.cxx
- Test program dyntest.cxx
- Do the problems listed below. Feel free to ask the TA
questions about the problems. Actively working on the lab
assignment during the lab session is required. Don't worry
if you can't finish the full assignment before the lab session
is over. You can finish afterwards.
Copy the files in /cs/cs2005/samples/lab2/ to one of your own
personal directories. Study the test program source file dyntest.cxx.
This program constructs two DynStuff objects named dyn1 and dyn2,
prints the contents of dyn1 and dyn2,
modifies the contents of dyn2, and prints the final contents of
both dyn1 and dyn2.
Type make at the Unix prompt in the directory to which
you copied the files provided in /cs/cs2005/samples/lab2/.
This compiles the DynStuff class definition, compiles the
test program, links the DynStuff class implementation to it,
and produces an executable file named dyntest.
Run the executable file dyntest. Are the results consistent with
the expected behavior of the program based on the source code in
dyntest.cxx? (Answer: no).
Problems occur here because the DynStuff class definition uses
dynamic memory. The assignment dyn1=dyn2 invokes automatic
assignment mechanisms which merely copy the member variables
of dyn2 to the corresponding member variables of dyn1. Since
the member variable data is a pointer, this makes dyn1.data
point to the same storage area as dyn2.data. When dyn2 is
subsequently modified, the array dyn1.data is also affected,
since it's actually the same array as dyn2.data.
Fix the above problems by adding three new member functions
for the DynStuff class: a copy constructor, an overloaded
assignment operator, and a destructor. Debug your design
as needed, and test it by linking it with the test program
in dyntest.cxx. Refer to section 4.3 of Main and Savitch
for examples of similar functions in the context of a
dynamic Bag class.
Use any remaining time to work on HW2.