Spell
{
public:
// code
private:
Hero &hero;
}
Heal(const Hero& h)
{
public:
// code
protected:
// code
}
Heal::Heal(const Hero& h): hero(h)
{
//code
}
Spell
{
public:
// code
private:
Hero &hero;
}
Heal(const Hero& h)
{
public:
// code
protected:
// code
}
Heal::Heal(const Hero& h): hero(h)
{
//code
}
I am so thoroughly confused by the syntax you are using. Did you by any chance mean something more like this?
class Hero
{
// Awesome and clean code
};
class Spell
{
public:
// Awesome and clean interface
private:
friend class Hero; // Ouch, not too awesome
Hero &hero;
};
class Heal : public Spell
{
public:
Heal(const Hero&);
protected:
// Helper functions
};
Well, in order to pass a modifiable Hero pointer to Heal, you need to watch out for a couple of things.
One, you are passing a const Hero, which means you won't be able to modify it. Remove the const keyword if you want to modify the object.
Two, as far as I can tell, you're passing Hero to the wrong object. The member variable hero in Spell is declared private and trying to assign a value to it from Heal will generate a compiler error.
Try fixing those errors and see if you can get it to do what you want.
Yo dawg, don't even trip.
class Spell
{
public:
Spell(const Hero& h) : hero(h) { }
protected:
Hero &hero;
};
class Heal
{
public:
Heal(const Hero& h) : Spell(h) { }
};
Though, really, you probably shouldn't pass in Hero until the spell is ready to be used:class Spell
{
public:
Spell() { }
virtual void UseOn(Hero &hero) = 0;
};
class Heal
{
public:
Heal() { }
void UseOn(Hero &hero) override
{
float amountToHeal = float(hero.maxHealth) * 0.25f;
hero.health = (int)amountToHeal;
}
};
I see, thank you. It seems I have fixed the errors with the classes, but I don't if it's working yet because calling it is giving me an error now.
I removed const, as was mentioned, and I moved Hero& hero to the protected section of Heal. Then I have:
spells.push_back(new Heal(heroes.at(0)) );
spells is a vector made above. std::vector<Spell*> spells;
and heroes is the hero vector. std::vector<Hero*> heroes;
This just isn't working now. Am I calling it wrong?
error C2664: 'Heal::Heal(Hero &)' : cannot convert parameter 1 from 'Hero **' to 'Hero &'
I've tried adding & and * but that doesn't work either.
Yo dawg, don't even trip.
I am concerned about the ownership issues that this constructor is causing. How are you going to ensure the Hero reference remains valid? Can you guarantee that the Hero will not be deleted (presuming it is dynamically allocated), leaving an invalid reference? Servant's alternative approach is probably what you should be doing.
You should probably be using smart pointers or values, as it is clear you don't yet understand how raw pointers behave. You'll still need to learn the concepts, but smart pointers at least will help you start with good practises and, used exclusively, hopefully limit the kinds of mistakes that are possible.