Best way to extend a class?

DrEvil

FCRI Associate!
Reaction score
111
So I have a base class:

class Enemy{
int minDmg,maxDmg;
// other stuff....
}

say I want special enemies with certain different attacks or behaviours, what would be the best approach, which could let me still group the extended classes together as an 'enemy list' if possible?

class Bunny:Enemy{
void specialAttack();
}

like this is the first time I've really created a functional game... and I'm just trying to find out how I would go about in making these.

Thanks... Any help is welcome because well, I'm stumped!
 

s3rius

Linux is only free if your time is worthless.
Reaction score
130
You haven't said which language you're working with, but from the syntax I'll guess C++.

Now, polymorphy (which is what you're trying to use) makes use of abstraction in order to group a number of objects by the things they have in common.
If you have a Bunny-Enemy with a specialAttack() and a Bird-Enemy with a flyingAttack() then they have nothing in common. If you're treating them both simply as Enemies then specialAttack() and flyingAttack() are lost.

But they're both attacks, so we can use that as a common trait:


Code:
class Enemy{
 
    int minDmg, maxDmg;
 
public:
 
    virtual void attack() = 0;
 
}
 
class Bunny : public Enemy{
 
public:
 
    void attack(){
 
        specialAttack();
 
    }
 
private:
 
    void specialAttack(){
 
          //Bunny bite!
 
    }
 
}
 
class Bird : public Enemy{
 
public:
 
    void attack(){
 
        flyingAttack();
 
    }
 
private:
 
    void flyingAttack(){
 
          //Bird poo!
 
    }
 
}

If you want to keep a normal attack() then you can make your base class look like this:
Code:
class Enemy{
 
    int minDmg, maxDmg;
 
public:
 
    virtual void attack() = 0;
    virtual void otherAttack() = 0;
}

Another option is to use a AI function like
Code:
 virtual void performAction() = 0;
which decides on an action for us, like which attack to use.
If you want to group stuff into a common list (like an enemy-list) you always have to try to write your classes so that your base class has all the functions you need to call.
 

DrEvil

FCRI Associate!
Reaction score
111
Thank you s3rius!
It works great!

Also yes I was using C++, I guess it would be more helpful next time if I say what I'm using...
 
General chit-chat
Help Users
  • No one is chatting at the moment.

      The Helper Discord

      Members online

      No members online now.

      Affiliates

      Hive Workshop NUON Dome World Editor Tutorials

      Network Sponsors

      Apex Steel Pipe - Buys and sells Steel Pipe.
      Top