Pointer help

Hi guys,

Need a little help with a text based rpg I am working on. Here's the situation:

I have a base class called Player, and from this class I have two derived classes Warrior and Priest.

I create a party like so:

1
2
3
4
5
Player* player[PARTY_SIZE];

	player[0]=new Warrior("Mike",Dwarf);
	player[1]=new Cleric("John",Halfling);

Of course, during my adventures, I need to do battle with monsters, which is done with a battle function.


1
2
3
4
5
6
7
8
9
bool battle(Player** player, int player_count){

char choice;
if(choice==1)//attack;
if(choice==2)//cast spell;
etc.

}


Here's my problem. The Priest class has a "heal" function, which is not a member of Player or Warrior. When I am in the battle function, and going through the array of Players ie.

1
2
3
4
5
6
for(int i=0;i<party_size;i++){
player[i]->set_damage();//can do this

//but can't do this since "heal" is not a member of player
player[i]->heal();
}



How do I tell the compiler which object is the Priest so I can "cast" my heal spell? which to repeat is not a member of either Player or Warrior, but only Priest.

Thanks,

Mike
Provide a virtual function in Player
1
2
3
4
5
6
7
8
9
10
11
12
13
class Player
{
public:
  virtual void heal() { }
}

class Priest : public Player
{
  void heal()
  {
    health += healamount;
  }
}
I would not recommend adding a virtual function to Player unless it's something all Players can do. Since only the Priest can heal, having an interface for the Player to heal is folly, IMO.


I would work in more generic terms. If this is something that's done every turn... perhaps a generic "update" function would make more sense than individual calls to set_damage and heal:

1
2
for(int i=0;i<party_size;i++)
  player[i]->update();


Here, update() would be a virtual function in Player. For most classes it would just call set_damage... but for Priests it would call set_damage + heal
Use inheritance.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class cPlayer
{
public: 
cPlayer(){};

virtual void Update(){};
};

class cPreist : public cPlayer
{
public:
cPreist(){};

void Update()
{
Heal();   //call the priests heal spell
};

void Heal()
{
/*If input equals "heal" then add to the HP*/
};

};


if you do it like this then any archetype of player that can be created and added to the player array can call the same function, and when the program looks into the vtable it will call the appropriate function. From there you can have each player type call its own thing to do its own thing.
Thanks guys,

Did what you recommended and it works well. Did not go with the virtual in player as it seems a little clunky. But it's something I will keep in my programming arsenal in the future.

Thanks,

Mike
Topic archived. No new replies allowed.