Classes

I am doing some coding in my spare time and trying to make a text based game because I have nothing better to do. I'm having trouble with creating a function in one class that modifies a variable in another class, I'm not 100% sure on how to declare the variable in the other class. I've tried making it a friend and rearranging things but I haven't been able to come up with a solution.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
  class Player {
private:
	string Name;
	string gender;
	int str;
	int spd;
public:
	int health = 100; //can be upgraded later in the game

	void Gameover() {
		if (health == 0) {
			cout << "Game over..." << endl;
		}
	}

	void setName(string Pn) {
		Name = Pn;
	}

	void setStr(int Str) {
		str = Str;
	}

	void setGender(string G) {
		gender = G;
	}

	void setSpd(int Spd) {
		spd = Spd;
	}

	void healthupgrd(int health) {
		health + 10;
	}
};

class Demon { //basic enemy type
private:
	string Name = "Demon";
	string descr = "Deep black with red lines that creep up and down its back and thighs.";
	int LAtkStr = 15; //light attack strength
	int HAtkStr = 30; //heavy attack strength
	int Player::health;
public:
	void HAtk() { //Heavy attack
		cout << "The Demon extends claws from its gnarled feet and lashes out in a vicious strike." << endl;
		health - HAtkStr;
		cout << "Health: " << health << endl;
	}

	void LAtk() { //Light attack
		cout << "The Demon used its clawed fingers to slash your chest" << endl;
		health - LAtkStr;
		cout << "Health: " << health << endl;
	}
};
If you want the Demon to be able to attack a Player, one option is to pass the player as a parameter to your attack functions.

1
2
3
4
void HAtk(Player& player)
{
    player.health -= HAtkStr;
}


1
2
3
4
5
6
Player player;

Demon demon;
demon.HAtk(player);

std::cout << player.health << std::endl;
Thanks, this was really helpful.
Topic archived. No new replies allowed.