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;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.