0

I'm having problems with the code below. I figured since Monster1=new Orc 's attack function can't know whether it's attacking a Troll or Goblin since it accepts an Entity pointer as an argument. But having the be_attacked functions doesn't help either

#include<iostream>
using namespace std;

class Entity

{

public:

    virtual void attack(Entity* victim) = 0;

    virtual void be_attacked(Orc* aggressor) = 0;

    virtual void be_attacked(Troll* aggressor) = 0;

    virtual void be_attacked(Goblin* aggressor) = 0;

};


class Orc: public Entity

{

public:

    virtual void attack(Entity* victim) { victim->be_attacked(this); }

   virtual  void be_attacked(Orc* aggressor) {cout<<"orc attacks orc!"<<endl; }

    virtual void be_attacked(Troll* aggressor) { cout<<"troll attacks orc"<<endl; }

    virtual void be_attacked(Goblin* aggressor) { cout<<"goblin attacks orc"<<endl; }

};


class Troll: public Entity

{

public:

    virtual void attack(Entity* victim) { victim->be_attacked(this); }

    virtual void be_attacked(Orc* aggressor) { cout<<"orc attacks troll"<<endl; }

    virtual void be_attacked(Troll* aggressor) { cout<<"troll attacks troll"<<endl; }

    virtual void be_attacked(Goblin* aggressor) { cout<<"goblin attacks troll"<<endl; }

};


class Goblin: public Entity

{

  virtual void attack(Entity* victim) { victim->be_attacked(this); }

    virtual void be_attacked(Orc* aggressor) { cout<<"orc attacks goblin"<<endl; }

   virtual  void be_attacked(Troll* aggressor) { cout<<"troll attacks goblin"<<endl; }

    virtual void be_attacked(Goblin* aggressor) { cout<<"goblin attacks goblin"<<endl; }

};


int main()
{
    Entity* monster1 = new Orc;

    Entity* monster2 = new Troll;


    monster1->attack(monster2); // calls void Orc::attack(Entity*) which in turns calls Troll::be_attacked(Orc*)

return 0;
}
2
Contributors
1
Reply
2
Views
4 Years
Discussion Span
Last Post by vijayan121
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.