joshuaegclark
joshuaegclark

Reputation: 3921

C++ Non-changing member variables with sub-class specific values

My Class Hierarchy is thus: BaseClass (is an abstract class) then it has three subclasses that inherit from it: ArcaneWarrior, Guardian, Magi.

I want to have two non-changing values for DefaultHealth and DefaultMana that are specific to each subclass as they will all have different values for both variables.

I guess I'm just looking for the best/most efficient way to do this.

Should I just have two virtual functions in the base class to return DefaultHealth and DefaultMana, and in the subclasses hard code in the values I want?

I appreciate any insight

Upvotes: 3

Views: 231

Answers (2)

Xeo
Xeo

Reputation: 131799

My vote goes to const values in the base class and a protected constructor:

class BaseClass{
  const unsigned default_health;
  const unsigned default_mana;

protected:
  BaseClass(unsigned def_hp, unsigned def_mp)
    : default_health(def_hp)
    , default_mana(def_mp)
  {
  }

public:
  // your functions...
};

class ArcaneWarrior
  : public BaseClass
{
public:
  ArcaneWarrior()
    : BaseClass(200, 50)
  {
  }

  // ...
};

This is superior to the virtual function approach in 2 ways:

  • No virtual dispatch at runtime (no overhead)
  • true const-ness (those values can't be changed, ever)

Virtual functions don't give you const-ness, see this example:

class BaseClass{
public:
  virtual unsigned GetDefaultHealth() const = 0;
  virtual unsigned GetDefaultMana() const = 0;
  // ...
};

class ArcaneWarrior
  : public BaseClass
{
  unsigned default_health, default_mana;

public:
  virtual unsigned GetDefaultHealth() const{
    return default_health;
  }

  virtual unsigned GetDefaultHealth() const{
    return default_mana;
  }

  void SetDefaults(unsigned health, unsigned mana){
    default_health = health;
    default_mana = mana;
  }
};

Upvotes: 5

Seth Carnegie
Seth Carnegie

Reputation: 75130

Yes, that's really the best and most straightforward way to do it. With virtual functions, you get both the "non-changing"-ness you want, along with being able to determine that value through a pointer (or reference) to the base class without knowing the exact type.

Upvotes: 2

Related Questions