2

I'm making a game. I plan on having 4 enemy types. I already made a class for one of them.

I'm new to C++ and I always was confused about Polymorphism and how and when to use it.

I need to know how I could create a class that acts as a base for all 4 of the enemy classes.

I know that with using OOP, one of the advantages is less code is used which means it's efficient. I'm not really asking for you to code a whole class for me, just asking how I could possibly use Polymorphism in this situation. Here is 1 of the 4 enemy classes. (They all will look exactly the same without Polymorphism, the only thing that will change is the chanceOfLoss variable).

class Punk
{
    public:
        Punk(Player player)
        {
            chanceOfLoss = 50;
            this->player = player;
        }
        bool Fight()
        {
            chanceOfWin = chanceOfLoss + player.GetWeapon();
            randNum = 1 + rand() % 100;

            if (randNum <= chanceOfWin)
            {
                return true;
            }
            return false;
        }
    private:
        Player player;
        int chanceOfLoss;
        int randNum;
        int chanceOfWin;
};
sehe
  • 374,641
  • 47
  • 450
  • 633
  • 9
    If the different enemy types only differ in the value of `chanceOfLoss`, then you shouldn't use a type hierarchy. Use a type hierarchy, if the enemy types behave differently. – nosid Aug 18 '13 at 17:37
  • I empathize on nosid comment: don't use inheritance in this case, just add a setter and a getter for `chanceOfLoss`. – Synxis Aug 18 '13 at 17:39
  • I think you are confusing core OOP principles here. [Polymorphism][1] in C++ gives you the ability to program on abstractions, rather on implementations. [Inheritence][2] gives you the ability to write common functionality for several classes. Please refer to the following question: [link][3]. [1]: http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming [2]: http://en.wikipedia.org/wiki/Inheritance_%28object-oriented_programming%29 [3]: http://stackoverflow.com/questions/10973949/difference-between-inheritance-and-polymorphism –  Aug 18 '13 at 17:43

1 Answers1

2

The following is an example of how you can use Polymorphism in this situation. You should consider if it is the best choice, depending on all design considerations.

class BaseEnemy will be the base class of your enemies. Each enemy type will inherit from it, and override the getChanceofLoss method. All enemies will share the same Fight method

class BaseEnemy
{
public:
   bool Fight()
   {
      chanceOfWin = getChanceOfLoss() + player.GetWeapon();
      ...
   }
   virtual int getChanceOfLoss() = 0;
}

class Punk: public BaseEnemy
{
public:
   virtual int getChanceOfLoss() { return 60; }    
}
Itsik
  • 3,920
  • 1
  • 25
  • 37