March 4, 2002
Reading assignment:
Deitel and Deitel - Read 8.8 and 8.10, concentrating in particular on memory allocation,
and the copy constructor
The copy constructor
- Called whenever you return an object from a function, whenever you pass an
object to a function, or define an object and initialize it to another object
of the same type.
- If it doesn't exist, then the default is to do a memberwise copy, which is fine
unless you have data members that are pointers
- To implement, create a constructor that takes a single parameter of the same
type as the object.
- For class Complex, here's a copy constructor
Complex::Complex(const Complex &c)
{
real = c.real;
imag = c.imag;
}
Implementing the assignment operator and copy constructor in Program 4
- Since our classes contain pointers to objects, the assignment operator and
copy constructor must be implemented, and in a nontrivial way
- The assignment operator for StudentRec should first check, as always,
that (this != *right_operand). Then it should do a memberwise copy, except
for the next-pointer. It should set the next pointer to 0.
- The copy operator for StudentRec does a member-wise copy except for the
next-pointer, just as the assignment operator, but it doesn't have to do the initial
address check
- The assignment operator for StudentGroup should first check, as always, that
(this != *right_operand). Then it should create a duplicate copy of the
entire list, one node at a time. Here's an outline:
StudentRec *ptr // traverses the list we're trying to copy
StudentRec *prev_ptr, newstud; // keeps track of students in the new list
listhead = 0;
ptr = right_operand's listhead;
while (ptr)
allocate a new StudentRec (with the data in the object *ptr)
if listhead==0, then this is the first student, so set listhead to this new
student
else, hook the previous object's next-pointer to this new object
update the prev_ptr to point to this new object
update ptr to point to the next student (in the list we're copying)
- The copy constructor for StudentGroup is just like the assignment operator
(creates a duplicate list), but it doesn't have to do the initial check
on addresses
Implementing the destructors in Program 4
- Since our classes contain pointers to objects, the destructor must be implemented
in a nontrivial way
- The destructor for StudentRec should set next to 0. Since a StudentRec represents
a single student, the destructor should do nothing more
- Since StudentGroup is responsible for lists, the StudentGroup destructor should
de-allocate the memory for every student in the list
Here's an outline:
StudentRec *ptr; // traverse the list we're destroying
StudentRec *nextptr; // remember who's next in the list
start at the beginning of the list: ptr = listhead
while (ptr)
set nextptr to ptr's next student
delete ptr;
ptr = nextptr;
reset size to 0