What is wrong with this virtual function?

I am working on polymorphism in C++ and I am trying to stimulate a random monster attack through an abstract class with two virtual functions. One for the attack itself, and one for inflicting damage. The attack is simply a void function that states what monster that has attacked you, and that works fine. But for the damage, I am getting the address rather than the double.

Why is that? Can someone help me?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
  class Enemy {
public:
	virtual void attack() = 0;
	virtual double setDamage(double a) = 0;
protected:
	double damage;
};

class Monster : public Enemy {
public:
	void attack() {
		std::cout << "Monster attack dealt you " << damage << std::endl;
	}
	double setDamage(double a) {
		srand(time(0));
		damage = (1 + (rand() % 6));

		return damage;
	}
};


1
2
3
4
5
6
7
8
9
int main() {
	Monster m;
	Enemy *enemy1 = &m;

	enemy1->attack();

	keep_window_open();
	return 0;
}
I can see that I am being stupid with my setDamage function (Which I am not even calling in main). I fixed it by removing the random number generating inside setDamage and did this for main:

1
2
3
4
5
	Monster m;
	Enemy *enemy1 = &m;

	enemy1->setDamage(20);
	enemy1->attack();


So back to dealing random damage, I simply did this in main:

1
2
3
4
5
6
7
	Monster m;
	Enemy *enemy1 = &m;

	srand(time(0));

	enemy1->setDamage((1 + (rand() % 6)));
	enemy1->attack();
Last edited on
Topic archived. No new replies allowed.