tags:

views:

71

answers:

1

Consider the following code :

#include <vector>
#include <iostream>

class a {
public:
    int i;
    void fun() { i = 999; }
    void fun() const { std::cout << "const fun" << std::endl; }
};

const a* ha() {
    return new a();
}

int main()
{
    std::vector<a *> v;
    v.push_back(new a());

    // cannot convert from 'const a *' to 'a *'
    // a* test = ha();

    std::vector<a *>::const_iterator iterator = v.begin();
    for (; iterator != v.end(); ++iterator) {
        // No enforcement from compiler? I do not want user to modify the content through
        // const_iterator.
        a* aa = (*iterator);
        aa->fun();
    }

    std::cout << (*(v.begin()))->i << std::endl;
    getchar();
}

May I know why I didn't get compiler error from

a* aa = (*iterator);

I wish compiler will tell me I need to use the const_iterator in the following way :

const a* aa = (*iterator);

Or, this is my wrong expectation on const_iterator?

+2  A: 

The const_iterator says that you can't modify the element in the container; that is, if you have a container of pointers, you can't change the pointer.

You aren't changing the pointer, you're changing the object pointed to by the pointer.

If you try to assign a new pointer to that element in the container, it will fail to compile:

*iterator = new a; // < Won't compile
James McNellis
Opps. I should declare the vector as std::vector<const a *> v too.
Yan Cheng CHEOK
Someone else had posted an answer to that effect; I guess it was deleted for some reason. In any case, you can do that, and it will give you the semantics you want in this case, but note well that you will then be unable to modify any of the elements in the container without using const_cast, even using a non-const iterator.
James McNellis