Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

C++ I have a creature base class, and 2 derived class from it- ant and doodlebug

ID: 3907482 • Letter: C

Question

C++

I have a creature base class, and 2 derived class from it- ant and doodlebug

I also have a gameboard class which has a 2d array where each element is either one of the 2 creatures or Null

If inside a function I want to move a creature across the gameboard, how would I go about doing so? and How would I check which creature is in which spot?

(I already made the function in each of the creature classes int ant::getType() { return 1) and doodlebug::getType{return 2) with the virtual function virtual int creature::getType() = 0; ) I also made copy constructor, assignment constructor and destrucor in creature class.

Example- I want to move an ant right.

Right now this is what I have and It is not working, what is the correct way to do this?

Code:

board::moveAntRight() {

if(this->grid[x][y] != NULL) {

if(this->grid[x][y]->getType() == 1) {

ant* thisAnt = (ant*)grid[x][y];

if(this->grid[x+1][y]==NULL) {

//ant moves right

grid[x+1][y] = thisAnt;

ant* newAnt = thisAnt;

delete thisAnt;

newAnt->turnsMoved++;

}

}

}

What am I doing wrong and what is the correct way to do this? Thanks

Explanation / Answer

board::moveAntRight() {

if(this->grid[x][y] != NULL) {

if(this->grid[x][y]->getType() == 1) {

ant* thisAnt = (ant*)(this->grid[x][y]);

if(this->grid[x+1][y] == NULL) {

//ant moves right

this->grid[x+1][y] = thisAnt;

// ant* newAnt = thisAnt;

// delete thisAnt;

// newAnt->turnsMoved++;

this->grid[x][y] = NULL;

thisAnt->turnsMoved++;

}

}

}

}

There was a missing bracket but I'm assuming that it was a copying mistake.
The mistake you were doing were using delete on thisAnt.
Since that is a pointer to the object and doesn't contain the object itself, you were deleting thisAnt itself.
Instead set grid[x][y] to point to NULL and make sure that the element next to it points to the same object.
There is no need to make a new pointer, pointing to the same obect as if you call delete on one, the other one would point to NULL.
I hope this made sense.