|
|
|
|
|
|
|
In addition to providing a default constructor and destructor, the compiler provides a default copy constructor. The copy constructor is called every time a copy of an object is made. |
|
|
|
|
|
|
|
|
When you pass an object by value, either into a function or as a function's return value, a temporary copy of that object is made. If the object is a user-defined object, the class's copy constructor is called. |
|
|
|
|
|
|
|
|
All copy constructors take one parameter: a reference to an object of the same class. It is a good idea to make it a constant reference, because the constructor will not have to alter the object passed in. For example: |
|
|
|
|
|
|
|
|
Here the CAT constructor takes a constant reference to an existing CAT object. The goal of the copy constructor is to make a copy of theCat. |
|
|
|
|
|
|
|
|
The default copy constructor simply copies each member variable from the object passed as a parameter to the member variables of the new object. This is called a member-wise (or shallow) copy, and although this is fine for most member variables, it breaks pretty quickly for member variables that are pointers to objects on the free store. |
|
|
|
|
|
|
|
|
New Term: A shallow or member-wise copy copies the exact values of one object's member variables into another object. Pointers in both objects end up pointing to the same memory. A deep copy, on the other hand, copies the values allocated on the heap to newly allocated memory. |
|
|
|
|
|
|
|
|
If the CAT class includes a member variable, itsAge, that points to an integer on the free store, the default copy constructor will copy the passed-in CAT's itsAge member variable to the new CAT's itsAge member variable. The two objects will then point to the same memory, as illustrated in Figure 13.1. |
|
|
|
|
|
|
|
|
This will lead to a disaster when either CAT goes out of scope. When the object goes out of scope, the destructor is called, and it will attempt to clean up the allocated memory. |
|
|
|
|
|
|
|
|
In this case, if the original CAT goes out of scope, its destructor will free the allocated memory. The copy will still be pointing to that memory, however, and if it tries to access that memory it will crash your program. If you're lucky. Figure 13.2 illustrates this problem. |
|
|
|
|
|