Possible Duplicate:
Why isn't the const qualifier working on pointer members on const objects?
Consider the following class that has a pointer member int *a
. The const method constMod
is allowed by the compiler even though it modifies the pointer data. Why doesn't the compiler make the pointer data const in the context of the const method? If a
was just an int we wouldn't be allowed to modify it in a const method.
class ConstTest
{
public:
ConstTest(int *p): a(p) {}
void constMod() const {
++(*a);
}
int *a;
};
I'm using g++ on linux.
Inside constMod()
, the declaration of a
is treated as:
int *const a;
which means the pointer has a constant value, not what it points to. It sounds like you are expecting it to be treated as:
const int *a;
which is different.
The pointer itself is not modified, only the data pointed. Even if it sounds strange from a human point of view, from a compiler point of view, none of the member of the class are altered.
It's just an ownership issue... there's no way the compiler can know if the pointed-to object is logically part of the object or not, so it's left for the programmer to police such issues. const
members are allowed to perform operations with side effects, as long as they don't modify their own apparent value. It's not really any different from letting them call say std::cout::operator<<()
or some other non-const function....
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With