Classes Communication

It seems like this should be basic but I am not seeing where I need to communicate the data here. This function gets called on by creature objects from two different classes. The "demonic attack" should be true for both class objects but for only one of the creature objects (balrog) should this block of code execute. My if condition is always true so this block of code is executing when both classes call it. How do I get the communication right so it only executes when the balrog class calls it?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
  
int Demon::getDamage() const 
	{
		int damage = Creature::getDamage(); 
		int damage2;
		bool balrog = true;
		

		if (rand() % 4 == 0) {

			cout << "Demonic attack inflicts 50 additional damage points!" << endl;
			damage2 = (rand() % getStrength()) + 1;

			if (balrog) {
				cout << "Balrog speed attack inflicts " << damage2 << " additional damage points!" << endl;
				damage += damage2;
				damage = damage + 50;
			}
			
		}
		return damage;
	}
int Demon::getDamage(bool balrog) perhaps. Whoever calls this function passes a parameter.
This is the code that calls it so there is no parameter passing.

1
2
3
4
5
6
7
8
9

cout << "Examples of " << b.getSpecies() << " damage: " << endl;
	for (int i = 0; i < 10; i++) {
		int damage = b.getDamage();
		cout << " Total damage = " << damage << endl;
		cout << endl;
	}
	cout << endl;
It's your code, yes? You can add parameters.
Last edited on
Sorry, to be more clear, the function is my code but the client program is provided by my instructor and I have to get the data to communicate accordingly.
What are the "two class objects" here? Is balrog a subclass of Demon? Are you supposed to be using polymorphism here?

If Creature is the base class of Demon, it sounds like the assignment is telling you to use polymorphism, but this is a guess.

The base class needs to define getDamage() as a virtual function, and both subclasses need to override it.
https://www.geeksforgeeks.org/virtual-function-cpp/
Last edited on
If you're meant to be using inheritance, I'd expect the code to look something like this:

1
2
3
4
5
6
7
8
int Balrog::getDamage() const 
{
        // Is this really meant to call the base class getDamage()?
 	int baseDamage = creature::getDamage();  // base damage value for all creatures?

        // HERE, add damage for balrog
        return damage;
}


You don't have a Balrog object call getDamage on a Demon object. The Balrog class has its own Damage function
Last edited on
I talked to my instructor and it turns out that I was misinterpreting the instructions and the statements for the different objects need to go in their respective classes.

You guys are right about the polymorphism and inheritance, and reading what you guys have to say is still helpful so I appreciate it!
Topic archived. No new replies allowed.