How do I use a pointer of a parent class to call a child's function?

How come when I use men[0]->attack(men[1]) it only calls the basic man attack function and not the derelict function? Is there any way around this?

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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
  #include <iostream>
#include <string>

using namespace std;

class man
{
protected:
	int strength;
	int health;
	string name;
public:
	man(int h, int s, string n) : health(h), strength(s), name(n) {};
	~man();
	int gethealth()
	{
		return health;
	}
	void sethealth(int h)
	{
		health = h;
	}
	void attack(man * enemyman)
	{
		enemyman->sethealth(enemyman->gethealth()-strength);
		cout<<"Attack!"<<endl;
	}
	void output_health()
	{
		cout<<health<<endl;
	}
};

class derelict : public man
{
private:
	int dirty;
public:
	derelict(int d,int h,int s, string n) : man(h, s, n), dirty(d) {};
	~derelict();
	void attack(man * enemyman)
	{
		enemyman->sethealth(enemyman->gethealth()-strength + dirty);
		cout<<"Gross Attack!"<<endl;
	}

};

class richman : public man
{
private:
	int greed;
public:
	richman(int g, int h, int s, string n) : man(h, s, n), greed(g) {};
	~richman();
	void attack(man * enemyman)
	{
		enemyman->sethealth(enemyman->gethealth()-strength + greed);
		cout<<"Money Attack!"<<endl;
	}
};
int main()
{ 
	man * Hobo = new derelict (5, 100, 5, "Kevin");
	man * Richy = new richman(5, 100, 10, "Matt");
	man * men[] = {Hobo, Richy};
	men[0]->attack(men[1]);
	men[1]->output_health();
	return 0;
}
Last edited on
Declare it as virtual.
virtual http://www.cplusplus.com/doc/tutorial/polymorphism/

And make the code const-correct int gethealth() const etc.
Topic archived. No new replies allowed.