|
|
|
|
|
|
|
In the class constructor's parameter list, we could just as well have declared msgStr as |
|
|
|
|
|
|
|
|
Remember that both of these declarations are equivalent as far as the C++ compiler is concerned. They both mean that the parameter being passed is the base address of a string. |
|
|
|
|
|
|
|
|
As you can see in the private part of the class declaration, the private variable msg is a pointer, not a char array. If we declared msg to be an array of fixed size, say, 30, the array might be either too large or too small to hold the msgStr string that the client passes through the constructor's parameter list. Instead, the class constructor will dynamically allocate a char array of just the right size on the free store and make msg point to this array. Here is the implementation of the class constructor as it would appear in the implementation file: |
|
|
|
|
|
|
|
|
#include <string.h> // For strcpy() and strlen()
.
.
.
Date::Date( /* in */ int initMo,
/* in */ int initDay,
/* in */ int initYr,
/* in */ const char* msgStr )
{
mo = initMo;
day = initDay;
yr = initYr;
msg = new char[strlen(msgStr) +1];
// Assert:
// Storage for dynamic string is now on free store
// and its base address is in msg
strcpy(msg, msgStr);
// Assert:
// Incoming string has been copied to free store
} |
|
|
|
|
|