const in Visual Studio .NET 2005
I am wondering about how the compiler handles const member functions. For example here is code that compiles in Visual Studio C++ .NET:
Relevant private members of class:
private
:int *set;inlinevoid setSetValue(int pos,int val )const;Implementation:
inline
void IntegerSet::setSetValue(constint pos,constint val )const{
*( set + pos ) = val;
}
set is dynamically allocated in the class constructor.
An assignment is being done to a const object but the compiler does not catch it.
Is there something I am missing, or is this a known problem?
Thank you.
[1520 byte] By [
Moorpark] at [2007-12-24]
Moorpark wrote: |
| I am wondering about how the compiler handles const member functions. For example here is code that compiles in Visual Studio C++ .NET: Relevant private members of class: private :int *set;inline void setSetValue( int pos, int val ) const;Implementation:inline void IntegerSet::setSetValue( const int pos, const int val ) const{ *( set + pos ) = val; } set is dynamically allocated in the class constructor. An assignment is being done to a const object but the compiler does not catch it. Is there something I am missing, or is this a known problem? |
|
AFAIK this is correct behavior. Example :
class A {
public :
int x;
int y;
int *set;
A(){
x = 128;
y = 256;
set = &x;
}
void aMethod(int pos) const {
*set = y; // is OK
set = &y; // is not OK
}
};
Regards
Sahir
I think I see the issue here. The first aMethod assignment is to a value that is referenced which is not considered part of the object. However, the second assignment is to the pointer variable which is part of the class.
Is this the right interpretation?
Thank you, Sahir, for your reply.
Moorpark wrote: |
| Is this the right interpretation? |
|
Yes.
Moorpark wrote: |
| Thank you, Sahir, for your reply. |
|
You are most welcome. Glad to be of help 
Regards
Sahir
I believe you got the right, the distinction is not directly based on class membership but rather on how pointer types work.
In the example set has type int*. In a const member function you get the corresponding constant type. But that's not int const* (pointer to const int), but int* const (constant pointer to a mutable int). Therefore set is a const lvalue, which cannot be assigned to (for builtin types, at least). However, dereferencing a int* const yields a modifiable lvalue of type int (again the pointer is constant no the object pointed to).
-hg