To answer your first question:
There are two reasons it is being done. firstly we want our class to hold the data in its own memory location rather than start pointing to the existing memory that was allocated outside of the class. if we dont put
strcpy
there and simple assign the pointer then that would result in a shallow copy and when the
char*
that was supplied from outside goes out of scope(or deleted) this class must have ended up pointing to some invalid location. secondly why is is not
buffer*
, simple reason for this is the starting address of char array needs to be passed to
strcpy
to copy the data from source to destination. if we pass
buffer*
that would actually be a pointer pointing to the starting address of the array, resulting in wring results and perhaps catastrophe.
strcpy(Buffer, InitialInput);
Now to answer your second question
const char * GetString()
{
return Buffer;
}
The reason this is returning a
*
is because we want the caller to get hold of complete string. that can only be done by passing the pointer to starting address. the caller can then simply use this address extract all chars till a
\0
and have all the string.
Now why is is
const
, we dont want the called to be able to change the string from outside and thus we are passing a
const
.
ADDITIONAL THOUGHTS:
I think this function
getString
is returning a pointer to a constant string so that the data can not be changed from outside but it is actually violating the basic encapsulation by passing the member pointer outside of the class. if he really wishes to so this I think this should ideally be like
const char * const GetString()
{
return Buffer;
}
I made the pointer constant too.
Note: C++ Gurus, please correct me if I am wrong or perhaps refine my understanding, i would really appreciate that.
eagerly awaiting response of experts on this.