This documentation is archived and is not being maintained.

CString Argument Passing

This article explains how to pass CString objects to functions and how to return CString objects from functions.

CString Argument-Passing Conventions

When you define a class interface, you must determine the argument-passing convention for your member functions. There are some standard rules for passing and returning CString objects. If you follow the rules described in Strings as Function Inputs and Strings as Function Outputs, you will have efficient, correct code.

Strings as Function Inputs

If a string is an input to a function, in most cases it is best to declare the string function parameter as LPCTSTR. Convert to a CString object as necessary within the function using constructors and assignment operators. If the string contents are to be changed by a function, declare the parameter as a nonconstant CString reference (CString&).

Strings as Function Outputs

Normally you can return CString objects from functions because CString objects follow value semantics like primitive types. To return a read-only string, use a constant CString reference (const CString&). The following example illustrates the use of CString parameters and return types:

class CName : public CObject
    CString m_firstName;
    char m_middleInit;
    CString m_lastName;
    CName() {}
    void SetData( LPCTSTR fn, const char mi, LPCTSTR ln )
        m_firstName = fn;
        m_middleInit = mi;
        m_lastName = ln;
    void GetData( CString& cfn, char mi, CString& cln )
        cfn = m_firstName;
        mi = m_middleInit;
        cln = m_lastName;
    CString GetLastName()
        return m_lastName;
CName name;
CString last, first;
TCHAR middle;
name.SetData( "John", 'Q', "Public" );
ASSERT( name.GetLastName() == "Public" );
name.GetData( first, middle, last );
ASSERT( ( first == "John" ) && ( last == "Public" ) );

See Also