const setter.

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;
}

Could you repeat your question one more but using the human language?!
the class foo has a const method. but that method can be used to modify foo's own members. thus circumventing the fact that the method is const...

so, does that make the program invalid by any standards?
In fact you have the following

1
2
3
4
int x;

const int *cp = &x;
int *p = &x;


You can change x using pointer p and you can not change x using pointer cp.

I think that your example does not break the standard.
const this is not used to access class member bar.
Last edited on
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.
1
2
@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;
Last edited on
Topic archived. No new replies allowed.