Hi,
i have a question related to the const modifier for class methods.
If I have a class like this:
class A
{
int b;
void printToScreen() const;
}
then I know that the printToScreen() method will not modify the b attribute.
But if I have
class A
{
int* b;
void printToScreen() const;
}
then it might as long as the adress b points to does not change.
Is there any way to specify that in this last case the value of b (the integer pointed to) cannot be changed? I am working on a program where almost all class attributes are pointers, and I would like to be able to enforce that the objects pointed to do not change for some methods.
There's no easy way. It's the reason there are both iterators and const_iterators.
The problem is that the const modifier gets placed in the wrong spot for you:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
int *p; //pointer to int
intconst *p; //pointer to const int
int *const p; //const pointer to int
intconst *const p; //const pointer to const int
//...
class blah
{
int *p; //for const methods this goes to "int const *p;"
//...
void dostuff() const
{//dirty fix:
intconst *const p = this->p; //mask the member p with a temporary
//...code...
}
};
It may look easy, but it isn't - when you need to change things around it would easily mess up your code.
then it might as long as the adress b points to does not change.
As the developer you are in control of the state of b when inside that function, all the const means is you promise to not change b inside that function.
Thanks for all these comments. @Athar, that is a very nice trick. The only drawback I see is that i would have to change the type signature of the methods I want to be const. I will think about it.
Wouldn't that mean that I can never ever modify b from A? The thing is, I would want to be able to modify b from some methods form A but not from others.