C++ – Polymorphism and passing

cgame development

I am writing a text based RPG, and I have three classes that inherit from a super class, they all have special attacks that they can perform, at the same time I have a class that holds the function which handles battles in my game.

Now how do I get the unique special abilities functions for whatever role the player chooses into the battle function?

Also I am using the vector.push_back method to handle how my sub classes are referenced.

Best Answer

You just need a virtual member function in your superclass:

class Superclass
{
    virtual void specialAbility() = 0;
};

And implementations in your subclasses:

class Subclass1 : public Superclass
{
    void specialAbility()
    {
        // Do something specific to this subclass...
    }
};

class Subclass2 : public Superclass
{
    void specialAbility()
    {
        // Do something specific to this subclass...
    }
};

Now when you do your battles, you could do something like this (edited to put in class):

class BattleDoer
{
    void doBattle(std::vector<Superclass*> combatants)
    {
        for (unsigned int index = 0; index < combatants.size(); index++)
        {
            combatants.at(index)->specialAbility();
        }
    }
};

This will cause the appropriate member function defined in the subclass to be called on each of the combatant objects.

Edit:

To populate your combatant list and call the doBattle() function, you can do something like this:

int main()
{
    Superclass* combatant1 = new Subclass1;
    Superclass* combatant2 = new Subclass2;

    std::vector<Superclass*> combatants;
    combatants.push_back(combatant1);
    combatants.push_back(combatant2);

    BattleDoer battleDoer;
    battleDoer.doBattle(combatants);

    delete combatant1;
    delete combatant2;
}

It is important to use pointers here. Only pointers and references can be used to provide polymorphism. You cannot have variables of type Superclass because it cannot be instantiated, you can only have references and pointers of type Superclass. Smart pointers should probably be used but I thought I'd keep it simple.

Related Topic