1

I'm trying to create a dynamic spell system for a game I'm developing: spells should consist of an archetype, e.g. area of effect and an effect, e.g. heal.

I have following (simplified) code:

class SpellEffect {
public:
    virtual void heal(int magnitude);
}

class SpellArchetype {
public:
    virtual void applyToArea(int sizeOfArea, void (*func)(int));
}

class Spell {
    SpellEffect effect;
    SpellArchetype archetype;
    int sizeOfArea;
    int magnitude;
public:
    void cast() {
        archetype.applyToArea(sizeOfArea, &effect.heal);
    }
}

However, since heal() is a member function this does not work.

I also have trouble passing the argument magnitude to the heal() function.

I found this question and the answer seems helpful. Yet it has been a while since I last used C++ and I can't figure out how to make it work in my case since the this is different.

Can someone please help me out?

S3k
  • 45
  • 7

1 Answers1

1

The correct syntax would be as shown below. Note that you can also use std::function.

class SpellEffect {
public:
    virtual void heal(int magnitude);
};

class SpellArchetype {
public:
//-------------------------------------------vvvvvvvvvvvvvvvvvvvvvvvvvvvvvv---->func is a pointer to a member function of class SpellEffect that has one int parameter and return type of void
    virtual void applyToArea(int sizeOfArea, void (SpellEffect::*func)(int));
};

class Spell {
    SpellEffect effect;
    SpellArchetype archetype;
    int sizeOfArea;
    int magnitude;
public:
    void cast() {
//----------------------------------------vvvvvvvvvvvvvvvvvv---->correct syntax instead of &effect.heal
        archetype.applyToArea(sizeOfArea, &SpellEffect::heal);
    }
};

In the above code, instead of having void (*func)(int) we have:

void (SpellEffect::*func)(int)

which means that func is a pointer to a member function of class SpellEffect that takes one int parameter and has the return type of void.

Jason
  • 36,170
  • 5
  • 26
  • 60