Read the first part of this discussion in yesterday's notes.
There's one more important detail you should be aware of when writing copy constructors -- the moment you declare your own copy constructor, you tell the compiler that you are not interested at all in its default copy constructor. That means that you have to make sure you take care of all the copying that needs to get done in your constructor. Don't just take care of pointers!
One other note about writing the copy constructor definition -- any member item that you leave unqualified is assumed to be a member of the object being constructed. To use the source's member, qualify the member with the source object's name. (Use the dot operator.)
So, that covers copy constructors. Well, almost. What if you want to copy
an object to another object that already exists? You can do that by
overloading the assignment operator (the = operator). The default
assignment
operator, like the default copy constructor, just makes a shallow copy, but
now
that's even worse, as you'll already have something at the end of the
pointers,
and that leads to a storage leak. So, basically what you have to do is write a
new public member function, void operator=(ObjType &s)
See
Assign.cpp. (Note: This is one rare case of an operator
that
is a member function rather than a friend function. Make sure you use it that
way.) There are several caveats involved here that weren't a problem in the
copy constructor.
To check that you aren't assigning an object to itself, use the test (this == &s), where s is the source object. Note that this test is different than (*this == s). The first will tell you if the two objects have the same address. If they do, they must be the same object. The second would make it necessary for you to have defined the == operator, and different objects can have equal member data.
Finally, a note on the Life program. When you're running a generation, you'll want to update each cell on whether it's alive or not. But if you change that information as you're counting the number of neighbors, you will screw up the count for some other cell down the line. One way to get around this is to make a copy of your whole colony, count the number of live neighbors on that, and update the cells on the new colony.
void colony::generation() { colony previous = *this; for (int r = 0; r < rows; r++) for (int c = o; c < columns; c++) int live = previous.liveNeighbors(r, c); ... }To Index Previous Next