FIX: Using String Constant as Default Argument Doesn't Work

Last reviewed: September 18, 1997
Article ID: Q124524
2.00 WINDOWS NT kbtool kbfixlist

The information in this article applies to:

   The Microsoft C/C++ Compiler (CL.EXE) included with
     - Microsoft Visual C++, 32-bit Edition, version 2.0
       on the following platform: x86

SYMPTOMS

Using a string constant to initialize a character pointer as a default parameter argument in a class member function does not work as expected. Instead of assigning the address of the string constant to the pointer, the compiler uses a different existing string constant.

CAUSE

This is a problem with character constants within a class definition, no matter how they are used. The compiler always uses the last string constant in the class definition.

RESOLUTION

To work around the problem, create a static character pointer that is set to the desired string constant and use that static variable to initialize the character pointer parameter of the constructor. Typically, string constants are defined globally in a header file so that they can be easily modified.

STATUS

Microsoft has confirmed this to be a bug in the Microsoft products listed at the beginning of this article. This problem was corrected in Microsoft Visual C++, 32-bit Edition, version 4.0.

MORE INFORMATION

You can use the following sample to reproduce this problem. The output of the sample code will be:

   Value of 'String' 1234567890 = 123456

In this case, the compiler used the first six characters of the "1234567890" string instead of using the "abcde" string.

Sample Code

/* Compile options needed: none
*/

#include <iostream.h>

class A { public:
   void Func(char* String = "abcde")
   {
      cout << "Value of 'String' " << "1234567890 = " << String << endl;
   }
};

void main()
{
   A a;
   a.Func();
}


Additional reference words: 2.00 9.00 buglist2.00
KBCategory: kbtool kbfixlist kbbuglist
KBSubcategory: CPPIss VCx86
Keywords : CPPIss VCx86 kbbuglist kbfixlist kbtool
Version : 2.00
Platform : NT WINDOWS
Solution Type : kbfix


THE INFORMATION PROVIDED IN THE MICROSOFT KNOWLEDGE BASE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. MICROSOFT DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING THE WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL MICROSOFT CORPORATION OR ITS SUPPLIERS BE LIABLE FOR ANY DAMAGES WHATSOEVER INCLUDING DIRECT, INDIRECT, INCIDENTAL, CONSEQUENTIAL, LOSS OF BUSINESS PROFITS OR SPECIAL DAMAGES, EVEN IF MICROSOFT CORPORATION OR ITS SUPPLIERS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. SOME STATES DO NOT ALLOW THE EXCLUSION OR LIMITATION OF LIABILITY FOR CONSEQUENTIAL OR INCIDENTAL DAMAGES SO THE FOREGOING LIMITATION MAY NOT APPLY.

Last reviewed: September 18, 1997
© 1998 Microsoft Corporation. All rights reserved. Terms of Use.