Let\'s say I\'m creating an OpenGL game in C++ that will have many objects created (enemies, player characters, items, etc.). I\'m wondering the best way to organize these since
I'm not sure I fully understand the question but I think you are wanting to create a collection of polymorphic objects. When accessing a polymorphic object, you must always refer to it by a pointer or a reference.
Here is an example. First you need to set up a base class to derive your objects from:
class BaseObject
{
public:
virtual void Render() = 0;
};
Then create the array of pointers. I use an STL set because that makes it easy to add and remove members at random:
#include
typedef std::set GAMEOBJECTS;
GAMEOBJECTS g_gameObjects;
To add an object, create a derived class and instantiate it:
class Enemy : public BaseObject
{
public:
Enemy() { }
virtual void Render()
{
// Rendering code goes here...
}
};
g_gameObjects.insert(new Enemy());
Then to access objects, just iterate through them:
for(GAMEOBJECTS::iterator it = g_gameObjects.begin();
it != g_gameObjects.end();
it++)
{
(*it)->Render();
}
To create different types of object, just derive more classes from class BaseObject. Don't forget to delete the objects when you remove them from the collection.