Article ID: 149324 - Last Review: July 5, 2005 - Revision: 1.1

FIX: Modifying Const Temporary Object Doesn't Generate Error

This article was previously published under Q149324

On This Page

Expand all | Collapse all

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 does not 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

This bug was corrected in Microsoft Visual C++, version 6.0.

MORE INFORMATION

Sample Code

/* Compile options needed: None
*/ 

truct A {

 int m_i;

 A() { m_i = 0; };

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

truct 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);

}
				

APPLIES TO
  • Microsoft Visual C++ 4.0 Standard Edition
  • Microsoft Visual C++ 4.1 Subscription
  • Microsoft Visual C++ 4.2 Enterprise Edition
  • Microsoft Visual C++ 4.2 Professional Edition
  • Microsoft Visual C++ 5.0 Enterprise Edition
  • Microsoft Visual C++ 5.0 Professional Edition
Keywords: 
kbbug kbfix kbvc600fix KB149324
Retired KB ArticleRetired KB Content Disclaimer
This article was written about products for which Microsoft no longer offers support. Therefore, this article is offered "as is" and will no longer be updated.
 

Article Translations