Reputation: 451
I'm working on a game and I want to make a base Actor class that holds Stat values that are shared among a variety of Actor types, but I'm having an issue understanding how I can accomplish this without having the base class having a different Stats variable than the actor types...
This is exactly what I have made right now (as shown in the code)... However, I want to somehow make the BaseActor "stats" type become either a PlayerStats or a MonsterStats object when it is created...This way the PlayerActor and MonsterActor no longer need the different "monster_stats" and "player_stats" objects as they inherit the correct type from BaseActor. Is this possible? I'm thinking it can be done through templates, but I'm not too versed in those.
class BaseStats {
public:
int defense;
private:
};
class MonsterStats : public BaseStats {
public:
int drop_rate;
private:
};
class PlayerStats : public BaseStats {
public:
int attack_power;
private:
};
class BaseActor {
public:
BaseStats stats;
private:
};
class MonsterActor : public BaseActor {
public:
MonsterStats monster_stats;
private:
};
class PlayerActor : public BaseActor {
public:
PlayerStats player_stats;
private:
};
Upvotes: 0
Views: 50
Reputation: 249
Look for Jeffrey's answer for a better way. But since you wanted to do this through templates (which is not recommended): -
template <typename T>
class BaseActor {
public:
T stats;
};
class MonsterActor : public BaseActor<MonsterStatus> {
public:
};
class PlayerActor : public BaseActor<PlayerStatus> {
public:
};
Upvotes: 0
Reputation: 11400
Have PlayerStats
and MonsterStats
derive from BaseStats
. Have the constructor of each derived BaseActor
allocate the stats with:
MonsterActor::MonsterActor()
{
m_stats = make_shared<MonsterStats>();
}
and have
std::shared_ptr<BaseStats> m_stats;
in the base class.
Upvotes: 2