|
|
|
|
|
|
|
The constructor begins by copying the first three incoming parameters into the appropriate private variables. Next, we use the new operator to allocate a char array on the free store. (We add 1 to the length of the incoming string to leave room for the terminating \0 character.) Finally, we use strcpy to copy all the characters from the msgStr array to the new dynamic array. If the client code declares two class objects with the statements |
|
|
|
|
|
|
|
|
Date date1(4, 15, 1997, My birthday);
Date date2(5, 12, 1997, Meet Al);
.
.
. |
|
|
|
|
|
|
|
|
then the two class objects point to dynamic char arrays as shown in Figure 17-9. |
|
|
|
|
|
|
|
|
Figure 17-9 illustrates an important concept: a Date class object does not encapsulate an arrayit only encapsulates access to the array. The array itself is located externally (on the free store), not within the protective abstraction barrier of the class object. This arrangement does not violate the principle of information hiding, however. The only access to the array is through the pointer variable msg, which is a private class member and is therefore inaccessible to clients. |
|
|
|
|
|
|
|
|
Notice that the Date class allocates dynamic data, but we have made no provision for deallocating the dynamic data. To deal adequately with class objects that point to dynamic data, we need more than just a class constructor. We need an entire group of class member functions: a class constructor, a class destructor, a deep copy operation, and a class copy-constructor. One by one, we will explain each of these new functions. But first, here is the overall picture of what our new class declaration looks like: |
|
|
|
|
|
|
|
|
Figure 17-9
Class Objects Pointing to Dynamically Allocated Strings |
|
|
|
|
|