BUG: Modifying Const Temporary Object Doesn't Generate Error

Last reviewed: July 24, 1997
Article ID: Q149324
The information in this article applies to:
  • The Microsoft C/C++ Compiler (CL.EXE) included with: - Microsoft Visual C++, 32-bit Edition, versions 4.0, 4.1, 4.2, 5.0

SYMPTOMS

The compiler generates the following error when you invoke a non-const member function on a const object:

   error C2662: 'Set' : cannot convert 'this' pointer from 'const struct
   A *' to 'struct A *const '

However, it doesn't generate this error when you invoke a non-const member function on a const object that is returned by a function.

RESOLUTION

To work around this problem, make the function return a reference to const.

STATUS

Microsoft has confirmed this to be a bug in the Microsoft products listed at the beginning of this article. We are researching this problem and will post new information here in the Microsoft Knowledge Base as it becomes available.

MORE INFORMATION

Sample Code

   /* Compile options needed: None
   */

   struct A {
     int m_i;

     A() { m_i = 0; };

     void Set() {m_i = 5;}
   };

   struct B {
     A m_a;

     // Change the return type to 'const A &' to work around
     const A GetMember() const {return m_a;}
   };


   void TestFunc(const B & b)
   {
     const A a;

     // Next line correctly generates:
     // error C2662: 'Set' : cannot convert 'this' pointer from
     // 'const struct A *' to 'struct A *const '

     // a.Set(); // Uncomment this line to get the error

     // Next line does not generate the error even though
     // B::GetMember returns const A object.
     // Change the return type of B::GetMember to 'const A &'
     // to get the error.

     b.GetMember().Set();
   }

   void main()
   {
     B b;

     TestFunc(b);
   }
 

	
	


Keywords : CPPIss kbtool vcbuglist400 vcbuglist500
Version : 4.0 4.1 4.2 5.0
Platform : NT WINDOWS
Issue type : kbbug


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: July 24, 1997
© 1998 Microsoft Corporation. All rights reserved. Terms of Use.