I tried to create an array Entity[]
with elements Human
and Zomby
.
Entity ent[5];
ent[0].set("human");
ent[1].set("human");
ent[2].set("human");
ent[3].set("human");
ent[4].set("zomby");
or
Entity ent[5];
ent[0] = new Human();
ent[1] = new Human();
ent[2] = new Human();
ent[3] = new Zomby();
ent[4] = new Zomby();
delete[] ent;
They are in different classes because Human
and Zomby
need different ai functions. They are in the same array to compare them, like this:
for (int a = 0; a < entL; a++)
{
for (int b = 0; b < entL; b++)
{
ent[a].ai( ent[b] ); // process ai interaction with other entities
}
}
Is there a way for an array to have multiple types, or is there a better way to handle objects? Here's my example code:
class Entity // base class
{
public:
float x, y;
};
class Human : public Entity // sub-class
{
public:
void ai(Entity &n){}
};
class Zomby : public Entity // sub-class
{
public:
void ai(Entity &n) {}
};
int main(int argc, char **argv)
{
// create entities in one container
const int entL = 5;
Entity ent[entL];
ent[0] = new Human();
ent[1] = new Human();
ent[2] = new Zomby();
ent[3] = new Zomby();
ent[4] = new Zomby();
// inside game while-loop
for (int a = 0; a < entL; a++)
{
for (int b = 0; b < entL; b++)
{
ent[a].ai( ent[b] );
}
}
delete[] ent;
system("PAUSE");
return 0;
}
RESOLVED
I can make variants of functions in sub-classes like ai
using virtual
and override
.
class Entity // base class
{
public:
Position pos;
virtual void ai(Position& other) { }
};
class Human : public Entity // sub-class
{
public:
virtual void ai(Position& other) override {
// human-specific AI code
}
};
class Zomby : public Entity // sub-class
{
public:
virtual void ai(Position& other) override {
// zomby-specific AI code
}
};
Entity* ent[5];
ent[0] = new Human (); // set sub-class elements
ent[1] = new Zomby ();
ent[2] = new Zomby ();
ent[3] = new Zomby ();
ent[4] = new Zomby ();
ent[0]->ai(ent[1]->pos); // call human.ai() passing zomby.pos
delete[]* ent;
Now, an array-pointer of a base-class can store elements of sub-classes.