I know, it sounds silly. It occured to me that I could abuse a class's own const methods to set it's own members. It's kind of appalling, but is does this actually violate any standards?
1 2 3 4 5 6 7 8 9 10 11
class foo {
public:
void go( int* change ) const { *change = 8; };
int bar;
};
int main ( void ) {
foo fum;
fum.go( &fum.bar );
return 0;
}
not quite the same. none of my pointers or variables are const, just the method. what I was getting at is how it seems odd to have a const method change a member of the class it belongs to, which totally circumvents the purpose of it being const.
It doesn't actually change a member. It changes a parameter, which just happens to be a member.
This behavior is perfectly consistent. In order to do fum.go( &fum.bar );
fum has to be a non-const object. If it's not, the compiler will reject the call.
In other words, when passed a pointer to a member, foo::go() behaves exactly like a non-const function would.
@Brandon Captain
not quite the same. none of my pointers or variables are const, just the method
You are wrong. Declaring a method with the const qualifier means that access to class members are done through const foo * this that is a pointer. So you have two pointers in your method
const foo * this
and
int * change
you access to class member bar through pointer change which points to mutable data.
if you would use implicitly this as for example
bar = 8; you would get an error because record bar = 8; is equivalent to this->bar = 8;