Game Development Stack Exchange is a question and answer site for professional and independent game developers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I am having a problem on the console game I am making. How can I decrease the health of the character or enemy with loopings? My code goes like this by the way for example:

class RPG_Scene_Battle {
  RPG_Scene_Battle(float ini_health) : health (ini_health){};
  float getHealth()
      return health;

  void setHealth(float rpg_val){ health = rpg_val;};

  float health;

float conductDamage(RPG_Scene_Battle rpg_tr, float damage) {
  rpg_tr.setHealth(rpg_tr.getHealth() - damage);
  return rpg_tr.getHealth();

how can I do a do while loop to decrease the player and enemy's hp without returning the method? because returning the method conductDamage under the do loop would return the same value and not decrease constantly.

share|improve this question

The problem is that the conductDamage function uses a new copy of the RPG_Scene_Battle object on each invocation (the parameter is passed by value), you need to pass a reference to the object instead. Simplest way of doing this is to change the signature of the function to

float conductDamage(RPG_Scene_Battle &rpg_tr, float damage)
share|improve this answer
would it not copy the same function when we loop it? – Angel Aug 12 '12 at 16:34
In the loop I assume you pass the same RPG_Scene_Battle object to conductDamage(), if you don't use pass-by-reference as described above the private object field health is only modified for the copy of the object - not the original object. This leads to the same value being returned on each invocation of conductDamage(). – johlo Aug 12 '12 at 16:45
@Angel: Using a pass-by-reference speeds up the application tremendously too. Due to not copying all data into a new part of memory. So it is almost always the better choice for games that uses a loop. – user18479 Aug 12 '12 at 18:43

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.