|
|
|
|
|
|
|
Creating boots from frisky |
|
|
|
|
|
|
|
|
Analysis: On lines 619, the CAT class is declared. Note that on line 9 a default constructor is declared and on line 10 a copy constructor is declared. |
|
|
|
|
|
|
|
|
On lines 17 and 18, two member variables are declared, each as a pointer to an integer. Typically, there'd be little reason for a class to store int member variables as pointers, but this was done to illustrate how to manage member variables on the free store. |
|
|
|
|
|
|
|
|
The default constructor, on lines 2127, allocates room on the free store for two int variables and then assigns values to them. |
|
|
|
|
|
|
|
|
The copy constructor begins on line 29. Note that the parameter is rhs. It is common to refer to the parameter to a copy constructor as rhs, which stands for right-hand side. When you look at the assignments in lines 33 and 34, you'll see that the object passed in as a parameter is on the right-hand side of the equal sign. Here's how it works: |
|
|
|
|
|
|
|
|
On lines 31 and 32, memory is allocated on the free store. Then, on lines 33 and 34, the value at the new memory location is assigned the values from the existing CAT. |
|
|
|
|
|
|
|
|
The parameter rhs is a CAT that is passed into the copy constructor as a constant reference. The member function rhs.GetAge() returns the value stored in the memory pointed to by rhs's member variable itsAge. As a CAT object, rhs has all the member variables of any other CAT. |
|
|
|
|
|
|
|
|
When the copy constructor is called to create a new CAT, an existing CAT is passed in as a parameter. |
|
|
|
|
|
|
|
|
Figure 13.3 diagrams what is happening here. The values pointed to by the existing CAT are copied to the memory allocated for the new CAT. |
|
|
|
|
|
|
|
|
On line 47, a CAT is created, called frisky. frisky's age is printed, and then his age is set to 6 on line 50. On line 52, a new CAT is created, boots, using the copy constructor and passing in frisky. Had frisky been passed as a parameter to a function, this same call to the copy constructor would have been made by the compiler. |
|
|
|
|
|
|
|
|
On lines 53 and 54, the ages of both CATs are printed. Sure enough, boots has frisky's age, 6, not the default age of 5. On line 56, frisky's age is set to 7, and then the ages are printed again. This time frisky's age is 7 but boots' age is still 6, demonstrating that they are stored in separate areas of memory. |
|
|
|
|
|