PRB: Can't Initialize Non-const Reference with Temp. Object

ID: Q91668


The information in this article applies to:


SUMMARY

If 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 const
Using 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 &'
Using the 32-bit Microsoft C/C++ compiler 6.0, the error appears as follows:
error C2664: 'Test' : cannot convert parameter 1 from 'char [6]' to 'class szString &' A reference that is not to 'const' cannot be bound to a non-lvalue


MORE INFORMATION

If 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


Keywords          : kbLangCPP kbVC100 kbVC150 kbVC151 kbVC200 kbVC210 kbVC400 kbVC500 kbVC600 
Version           : 
Platform          : MS-DOS NT WINDOWS 
Issue type        : kbprb 

Last Reviewed: July 14, 1999