Summary: Think of CString objects as actual strings.
Even though they are dynamically growable objects, CString objects act like built-in primitive types and simple classes. Each CString object represents a unique value. CString objects should not be thought of as pointers to strings but as the actual strings.
The most obvious consequence of value semantics is that the string contents are copied when you assign one CString to another. Thus, even though two CStrings may represent the same sequence of characters, they do not share those characters. Each CString has its own copy of the character data. When you modify one CString object, the copied CString object is not modified, as shown by the following example:
CString s1, s2;
s1 = s2 = "hi there";
if( s1 == s2 ) // TRUE - they are equal
...
s1.MakeUpper(); // does not modify s2
if( s2[0] == 'h' ) // TRUE - s2 is still "hi there"
Notice in the example that the two CString objects are considered to be “equal” because they represent the same character string. The CString class overloads the equality operator (==) to compare two CString objects based on their value (contents) rather than their identity (address).
·To specify CString formal parameters correctly:
For most functions that need a string argument, it is best to specify the formal parameter in the function prototype as a pointer to const char (const char* or const char FAR*) instead of a CString. With a formal parameter specified as a pointer to const char, you can pass either a pointer to a char array, a literal string ("hi there"), or a CString object. The CString will be automatically converted to a pointer to const char. Any place you can use a pointer to char, you can also use a CString.
You can also specify a formal parameter as a constant string reference (that is, const CString&) if the argument will not be modified. Drop the const modifier if the string will be modified by the function. If a default null value is desired, initialize it to the null string (""), as shown below:
void AddCustomer( const CString& name,
const CString& address,
const CString& comment = "" );
For most function results, you can simply return a CString object by value.