String::String(const char * Value)
{
if( Value == NULL ) // Use "" if Value is NULL.
{
Get_Buffer(0); // allocate storage for Buffer
Buffer[0] = '\0'; // the built-in operator []
}
else
{
Get_Buffer( strlen( Value ) ); // strlen from <string.h>
for(int i = 0; i < Buffer_Len; i++ )
Buffer[i] = Value[i];
}
}
- Note that = NULL initialization is done in the class declaration,
but not in the constructor definition.
- This constructor takes a char * and constructs a String object.
- Called as String x("abc"); or String x;
The String constructor calls Get_Buffer which allocates storage for Buffer.
QUESTION: What happens when the call is String x?ANSWER:
This is the copy constructor for string.String::String( const String & Value )
{
Get_Buffer( strlen( Value.Buffer ) );
for( int i = 0; i < Buffer_Len; i++ )
{
Buffer[ i ] = Value.Buffer[ i ];
}
}
QUESTION: Why is it important to write this
copy constructor ourselves, and not rely on the compiler's copy constructor?ANSWER:
- The destructor ~String is defined in the class definition
It simply de-allocates the storage set aside for Buffer.