OOP Game - updating list of object while in an objects update function

closed account (96AX92yv)
Im quite new to oop and having trouble with creating new objects inside of others. In my game, I require a bullet to be created in the players update function. The problem is that I have no idea how to add the created object (bullet) to the game list in order for it to be updated. To update game objects I use this:

1
2
for(iter = objects.begin(); iter != objects.end(); ++iter)
					(*iter)->Update();


I thought of returning the bullet object in the function but that would increase difficulty of updating all other objects as only specific game objects would return values.
to create a bullet I use:

Bullet *bullet = new Bullet(*Weapon::bullet);

found the players update function

I need to add this object into the objects list but am unsure how to do this as it is contained in the main.cpp file.
Can anyone specify a way in which these created objects can be add to the list?
Last edited on
that would increase difficulty of updating all other objects as only specific game objects would return values.

?

You have a list of objects and they all have function Update(), but for some the function returns void and for others a pointer?

Make them all return a pointer value. Remember, nullptr is a pointer value too.
closed account (96AX92yv)
Thanks for reply.
would this change the update section to:

1
2
3
4
5
6
for(iter = objects.begin(); iter != objects.end(); ++iter)
				{
					GameObject* newObject = (*iter)->Update();
					if (newObject != nullptr)
						objects.push_back(newObject);
				}
Almost.

What can the push_back() do to iterators? Invalidate. Do you remember why?
closed account (96AX92yv)
because they are pointers?

does it still apply to lists not vectors?

std::list<GameObject *> objects;
The list is safe, vector is not. See the reference documentation of each container.

The vector::push_back can cause a reallocation (and move of existing elements) of vector's internal array.


Consider also storing smart pointer objects in the container, rather than raw pointers.
closed account (96AX92yv)
I didnt know about smart pointers but i just read some documentation on them. Is the purpose in smart pointer just to automatically destroy pointers?

also, i had another idea on creating objects. What if there was a global function called Instantiate that is called whenever an object is created. This can be defined in the main.cpp file as:

1
2
3
4
void Instantiate(GameObject* newObject)
{
objects.push_back(newObject);
}


would this be a better method?
Last edited on
Topic archived. No new replies allowed.