PRB: Can't Initialize Non-const Reference with Temp. ObjectLast reviewed: September 30, 1997Article ID: Q91668 |
The information in this article applies to:
SUMMARYIf a temporary object is passed to a function that takes a reference to an object as a parameter, that reference must be a const reference. If this is not the case, the 16-bit Microsoft C/C++ compiler will generate the following error:
error C2607: 'initializing' : cannot implicitly convert a 'char [6]' to a non-const 'class ::szString __near &'Using the 32-bit Microsoft C/C++ compilers 2.x and 4.x, the error appears as follows:
error C2607: 'initializing' : cannot implicitly convert a 'char [6]' to a 'class ::szString &' that is not constUsing the 32-bit Microsoft C/C++ compiler 5.0, the error appears as follows:
error C2664: 'Test' : cannot convert parameter 1 from 'char [6]' to 'class szString &' MORE INFORMATIONIf the function is called with a parameter that is not of the type that the function expects, a temporary object is created using the appropriate constructor. This temporary object is then passed to the function. In this case, the temporary object is used to initialize the reference. In previous versions of the language, all references were able to be initialized by temporary objects. This behavior is now being phased out, hence the error given by the Microsoft C/C++ compiler. The code below demonstrates this error by calling Test with a string literal. Because the parameter is a szString reference, an object must be created by the appropriate constructor. The result is a temporary object that cannot be used to initialize the reference.
Sample Code
/* Compile options needed: for 16-bit - /f /Od /Zi * for 32-bit - none */ #include <iostream.h> #include <string.h> class szString { int slen; char *str; public: szString(const char *); int len() const { return slen; } }; void Test(szString &a) { cout << a.len();} szString::szString(const char * newstr) { slen=strlen(newstr); str = new char[slen + 1]; strcpy(str, newstr); } void main(void) { Test("hello"); } |
Additional query words: 8.00 8.00c 9.00 9.10
© 1998 Microsoft Corporation. All rights reserved. Terms of Use. |