Reputation: 3
this may be an amateur question, but here it goes. I have three clases:
DrawableObject:
class DrawableObject
{
private:
int x;
//...
public:
int getX();
//...
}
FormElement which inheirts from DrawableObject:
class FormElement : public DrawableObject
FormElement has a method called wasPushed:
bool FormElement::wasPushed(SDL_Event event)
{
bool wasPushed =
(
( event.motion.x >= getX()) //Inherited getX()
&& // Blah blah...
) ? true : false;
return wasPushed;
}
Finally, TextField, which inheirts from FormElement:
class TextField : public DrawableObject
I also have a class, named Form:
class Form {
public:
list<FormElement*> getFormElements();
void generateForm();
private:
list<FormElement*> formElements;
}
Form adds some TextFields to its list, in its generateForm() method:
void Form::generateForm() {
TextField *aTextField = new TextField(10, 10, 120);
this->formElements.push_back(aTextField);
}
Later, it tries to iterate it:
for(list<FormElement*>::iterator it = getFormElements().begin()
; it != getFormElements().end()
; ++it)
{
if ( (*it)->wasPushed(theEvent) )
{ //Etc.
Well, the program exits, when it tries to access getX() from wasPushed method.
Could anyone please tell me why? What am I defining wrong?
I thank you very much. Martín.
Upvotes: 0
Views: 55
Reputation: 64308
You are returning the list by value:
list<FormElement*> getFormElements();
it should be by reference:
list<FormElement*> &getFormElements();
When you return by value, you are getting a temporary copy of the list.
So in this code:
for(list<FormElement*>::iterator it = getFormElements().begin()
; it != getFormElements().end()
Your begin and end iterators are pointing to two different copies of the list. Also, those temporary copies will be destroyed before you ever have a chance to iterate over them.
You could also use the formElements member directly:
for(list<FormElement*>::iterator it = formElements.begin()
; it != formElements.end()
; ++it)
Upvotes: 1