Eco Simulation  «Prev  Next»
Lesson3 Lifeform abstract base class
ObjectiveExamine the abstract base class for the lifeforms in the ecological simulation.

Lifeform Abstract Base Class

In our primitive ecological simulation, the "world" will have different forms of life interacting. We will begin by examining the abstract base class for the lifeforms, which are living. Its interface will be inherited by various forms of life.
In this simulation, foxes are the archetypal predator and rabbits are the prey. The rabbits will eat grass.

//Predator-Prey simulation using class living
const int  N = 40;     //size of square board
enum state { EMPTY, GRASS, RABBIT, FOX, STATES };
const int DRAB = 3,   // used to determine lifespan
DFOX = 6,   // used to determine lifespan
CYCLES = 5; // number of cycles
// simulation will run

class living;                 //forward declaration
typedef living* world[N][N];  //world is simulation

class living {                //what lives in world
public:
virtual state  who() = 0;  //state identification
virtual living*  next(world w) = 0;  //compute next
protected:
int   row, column;  //location
void  sums(world w, int sm[]);
//sm[#states] used by next()
};

void living::sums(world w, int sm[]){
int  i, j;

sm[EMPTY] = sm[GRASS] = sm[RABBIT] = sm[FOX] = 0;
for (i = -1; i <= 1; ++i)
for ( j = -1; j <= 1; ++j)
sm[w[row + i][column +j] -> who()]++;
}

Two pure virtual functions

There are two pure virtual functions. Virtual functions incur a small added runtime cost over normal member functions. Therefore, we use them only when necessary to our implementations.
There is also one ordinary member function, sums(). Our simulation will have rules for deciding who goes on living in the next cycle based on the populations in the neighborhood of a given square. These populations are computed by sums().
Next, we will look at the inheritance hierarchy of living.

Shares
WhatsAppFacebookXPinterestRedditSumoMe