Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't C++ enforce const on pointer data? [duplicate]

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.

like image 393
Matthew Smith Avatar asked May 10 '11 05:05

Matthew Smith


3 Answers

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.

like image 55
Greg Hewgill Avatar answered Nov 15 '22 17:11

Greg Hewgill


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.

like image 20
Bruce Avatar answered Nov 15 '22 16:11

Bruce


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....

like image 23
Tony Delroy Avatar answered Nov 15 '22 18:11

Tony Delroy