-
communication
I have these classes and I want them to communicate without using global variables. This is how I solved it.
Code:
#include <iostream>
#include <vector>
class Player {
private:
unsigned short hp;
public:
void damage();
Player(): hp{100} {}
};
void Player::damage() {
--hp;
}
class Enemy {
protected:
unsigned short hp;
public:
virtual void update(Player&)=0;
Enemy(): hp{} {}
virtual ~Enemy(){}
};
class Bat: public Enemy {
public:
void update(Player&);
};
void Bat::update(Player& player) {
player.damage();
}
int main() {
Player player;
std::vector<Enemy*> enemies;
enemies.push_back(new Bat);
for(unsigned int i{}; i<enemies.size(); ++i)
enemies[i]->update(player);
delete enemies[0];
}
Is there a smarter design decision than this? The crucial part beeing having to pass player to void Bat::update(Player& player).
I also wrote a Player class with static members and friendship with Enemy but that didn't include Bat for some reason.
Any suggestions would be helpful, thanks.
-
I don't see a problem with the messaging system you have in place (although at the moment the computer is a cheating bastard). Passing player shouldn't be a problem as monsters should be able to damage anyone in the party. No reason to be clever, correct is better than cute.
>> I also wrote a Player class with static members and friendship with Enemy but that didn't include Bat for some reason.
Did you happen to read Bubba's post in your earlier thread?
Concerning the rest of the code: Specifying a reference counting pointer like boost::shared_ptr<Enemy> as vector's type would make things a lot easier for you in terms of memory management without breaking polymorphism. It's never to early to learn about smart pointers... IMO proficient use in these promotes a better understanding of the subject than insisting memory management is something we do well with raw pointers.