Reputation: 1437
I would like to access members of objects contained in a list of such objects.
I have a class CApp
with a member std::list<Particle> PList
serving as a list of particles.
A class Particle
has a member void Update()
which from my understanding of const can't be const because it affects the instance (euler integration and stuff).
I would like to iterate through PList to update all of the particles.
A Particle constructor includes:
Particle::Particle(std::list<Particle>* PList_In) {
PList = PList_In;
PList->push_back(*this);
}
The following is called several times:
Particle(&PList);
So the list appears to be set up. As a side note, if anyone could explain what's actually there in terms of memory (pointers, references) at this point that would be great.
But basically this errs:
// Update all particles
std::list<Particle>::const_iterator iter;
for (iter = PList.begin(); iter != PList.end(); iter++) {
iter->Update();
}
with
error: passing ‘const Particle’ as ‘this’ argument of ‘void Particle::Update()’ discards qualifiers
Not sure what to do with this, if more information/explanation is required, let me know.
Thanks in advance!
Upvotes: 0
Views: 407
Reputation: 73443
By using const_iterator
you are telling the compiler that you are not going to use this iterator on methods which modify the pointed to objects. Whether a method modifies the object or not is determined by its const qualifier. For example if you have a method declaration like int get() const;
inside class A
then this method is guaranteeing that it will not modify objects of class A
. In your case it seems Update
is not having the const qualifier hence the compiler is complaining that you can not call a non-const function using a const_iterator
. You need to change the iterator type std::list<Particle>::iterator
.
As a side note consider passing the list
object by reference instead of using the pointer in your function.
Upvotes: 1
Reputation: 6365
By using const_iterator you say that you don't want to change list elements.
If you want to, use std::list::iterator.
Upvotes: 1