I am puzzled by the behaviour of the following code.
I have a dummy class with a vector member. I would also like an iterator member so I can access the vector in the various methods without having to declare a new one each time. It seems OK until I introduce a const method.
The test1 method uses the vector and the iterator members just fine.
The test2 method throws a compile error when I try to use the const_iterator member with the vector. However, if I declare a new const_iterator in the method it compiles.
Can someone please explain this behaviour.
Thanks
class dummy {
public:
std::vector<double> data;
// Declare iterators as members
std::vector<double>::iterator iterator1;
std::vector<double>::const_iterator const_iterator1;
void test1(){
iterator1 = data.begin();
}
void test2() const {
// const_iterator1 = data.begin(); // Fails
std::vector<double>::const_iterator const_iterator2 = data.begin(); // Compiles
}
};
You cannot change values of member variables in a const
function.
const_iterator1 = data.begin(); // Changes the value of const_iterator1 member variable
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments