Brian Boddaert Brian Boddaert -3 years ago 89
C++ Question

C++ class function fails to change variables

When calling buildingname.damagebuilding(34) the currenthealth would only decrease temporarily, the first print prints 100 the second prints 66 but after calling damagebuilding again it's reset to 100 again. currenthealth isn't set anywhere else but in the constructor.

Class:

class building {
public:
int maxhealth;
int currenthealth;
int cost;
int level;
int Posx;
int Posy;
building() {}
building(int h, int c, int x, int y) {
maxhealth = h;
currenthealth = h;
cost = c;
level = 1;
Posx = x;
Posy = y;
}

void damageBuilding(int h) {
if (currenthealth - h > 0) {
std::cout << " Before "+std::to_string(currenthealth);
currenthealth=currenthealth-h;
std::cout << "\n After " + std::to_string(currenthealth)+"\n";
}
else {
std::cout << "\n Building destroyed ";
}
}

};


Where it's called:

void fire(int x,int y) {
if (activeplayer == 1 && bulletsP1 > 0 && sgrid2[x][y] != 0) {
if (sgrid2[x][y] > 0 && sgrid2[x][y] < 9) {
for (std::list<cannon>::iterator it = cannonsP1.begin(); it != cannonsP1.end(); ++it) {
if (it->ID == bulletsP1) {
findbuilding(x, y).damageBuilding(it->damage);
}
}
}
bulletsP1--;
sgrid2[x][y] = grid2[x][y];
vgrid2[x][y] = 3;
}
}


Findbuilding:

building & findbuilding(int x, int y) {
if (activeplayer == 1) {

for each (building b in bgrid2)
{
if (b.Posx == x && b.Posy == y) {
return b;
}
}

}
//else if (activeplayer == 2) {
else {
for each (building b in bgrid)
{
if (b.Posx == x && b.Posy == y) {
return b;
}
}
}
}

Answer Source

Function

findbuilding(x, y)

returns instance of class building by value, it means you are modifying just the copy of an instance. You have to return pointer (*) or reference (&) to that instance, to get effect.


building findbuilding(int x, int y) {}

to

building & findbuilding(int x, int y) {}

There is your instance i with currenthealth = 100 in memory

+-----+-----+-----+-----+-----+
|     |     |  i  |     |     |
|     |     | 100 |     |     |
+-----+-----+-----+-----+-----+

if you return it by value copy, this cell is copied to another place in memory, iCpy

+-----+-----+-----+-----+------+
|     |     |  i  |     | iCpy |
|     |     | 100 |     |  66  |
+-----+-----+-----+-----+------+
               ^           ^
               |           --------------- You are modifying this copy
               --------------------------- The real instance stays unchanged

By passing an reference to this instance

+-----+-----+-----+-----+-----+
|     |     |  i  |     |     |
|     |     |  66 |     |     |
+-----+-----+-----+-----+-----+
               ^           
               -------------------------- You are modifying real instance
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download