inheritance. Saving functuanality base and derive classes.

Saving functuanality base and derive classes how to implement(/ rewrite this code )? Please help.
Other words , I want that if I call:
n.attack();
my output is : " I'm enemy class " and "ninja attack !!! "

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
#include <iostream>
using namespace std; 

class Enemy {
public: 
	 void attack ()
	{
		cout << " I'm enemy class " << endl;
	}

};

class Ninja :public Enemy 
{
	public: 
		void attack (){cout << "ninja attack !!! "<<endl;}
};

class Monster :public Enemy 
{
	public: 
		void attack (){cout << "monstar attack !!! "<<endl;}
};


int main () {
	
	Enemy e;
	e.attack();

	Ninja n;
	Monster m;

	Enemy *enemy1 = &n;
	Enemy *enemy2 = &m;
	enemy1->attack();
	enemy2->attack();

	cout << "!!!need this!!!" << endl;
	n.attack();



	system ("pause");
	return 0; // virtual member make this even easier 
}


Many thanks !
In your derived classes, write the attack function like this:

1
2
3
4
5
void attack ()
{
    Enemmy::attack();
    cout << "ninja attack !!! "<<endl;
}


That should give you what you want. This way, the derived class function will call the base class function before executing its own specialized behavior.

Last edited on
Many Thanks +100500 likes on your post !
Topic archived. No new replies allowed.