A friend and I are working on our first game engine in C++. We're both new to C++, but not to programming in general. Our current method of handling objects (things within the game, such as a player object) works fine, and is pretty fast! But I'm not sure if it's practical (or maybe there's a faster, more stable way?). So I'm going to post what we have (in a nutshell, obviously not the whole game engine, not even a part of it, just a small example of how this portion of it works), and I want to know what you, the experts, think about what we're doing.
So here's what I've got to demonstrate basic functionality:
#include <iostream>
using namespace std;
#define MAX_INSTANCES 10000
// The base object, that all our other objects will use as a parent.
class baseObject
{
public:
virtual void Step() {}
};
// An object specific to this game, derived from our base object so we can store it in our pointers
class anotherObject : public baseObject
{
public:
virtual void Step()
{
cout << "Hello!" << endl;
}
};
// Pointers for all instances in the game
baseObject*instances[MAX_INSTANCES];
// Whether an instance exists or not (whether we should process it in engineStep)
bool instanceExists[MAX_INSTANCES];
// Create an instance, and store it in a pointer, return the pointer array's id
int createInstance(baseObject*object)
{
// search for a pointer not in use already
int id;
for (id=0; id<MAX_INSTANCES; id++)
{
if (!instanceExists[id])
{
break;
}
}
if (id != MAX_INSTANCES) // did we find an empty pointer?
{
instances[id] = object;
instanceExists[id] = true;
}
else // if all pointers are full, set id so the function will return -1 (indicating error)
{
id = -1;
}
return id;
}
void engineStep()
{
// find all in-use pointers and execute the object's 'step' event within
for (int i=0; i<MAX_INSTANCES; i++)
{
if (instanceExists[i])
{
instances[i]->Step();
}
}
}
int main()
{
// this is just to demonstrate how it all works, we can create instances, and when step is called, each of their 'step' events will execute
createInstance(new anotherObject);
engineStep();
engineStep();
engineStep();
createInstance(new anotherObject);
engineStep();
// final output is 5 'Hello!'s
return 0;
}
Aside from the comments, here's some things to take note of:
1. Virtual functions. I don't really understand how they work... but they work! Bonus points goes to anyone who helps me understand those! :P
2. 10,000 pointers. The main reason I'm questioning our method.. we must allocate all these pointers when most people won't have 10,000 instances of each object in their game.
3. I'm not having any issues with this code, everything runs fine. I'm just wanting to know if this is absolute crap programming, and if so, what would be a better way to do this?
Thanks for your time.