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 they will be created and destroyed real-time based on time, player position/actions etc.
Here’s what I’ve thought of so far: I can have a global array to store pointers to these objects. The textures/context for these objects are loaded in their constructors. These objects will have different types, so I can cast the pointers to get them in the array, but I want to later have a renderObjects() function that will use a loop to call an ObjectN.render() function for each existing object.
I think I’ve tried this before but I didn’t know what type to initialize the array with, so I picked an arbitrary object type, then cast anything that wasn’t of that type. If I remember, this didn’t work because the compiler didn’t want me dereferencing the pointers if it no longer knew their type, even if a given member function had the same name: (*Object5).render() <-doesn’t work?
Is there a better way? How to commercial games like HL2 handle this? I imagine there must be some module etc. that keeps track of all the objects.
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:
Then create the array of pointers. I use an STL set because that makes it easy to add and remove members at random:
To add an object, create a derived class and instantiate it:
Then to access objects, just iterate through them:
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.