Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructing derived class from inherited variables

Perhaps the title is a bit confusing so I'll try my very best to make sure it's as clear as possible.

Basically, I'm trying to create a game where there is a abstract base class called "Creature" and has several derived fantasy creature classes under it.

Now my question is:

if I have a base class that has protected variables int strength and int armor, how can I construct a derived class using int strength and int armor so that they get their own value without actually defining strength and armor variables within that class?

Let me write the code that I'm trying to achieve.

class Creature
{
  public:
    Creature();
  private:
    int armor;
    int strength;
};

class Human: public Creature
{
   public:
      Human(int a, int b): armor(a), strength(b)
      {
      }
};

int main() 
{ 
  Human Male(30, 50);
  cout << Male.armor;
  cout << Male.strength;
  return 0;
}

How would I do this? I need to have armor and strength within the first class so I can't declare it in every derived class.

Any help is appreciated. Thank you!

like image 522
Somewhat Insane Avatar asked Aug 25 '26 20:08

Somewhat Insane


2 Answers

You can create a constructor in base class that takes str and armor as parameters and then pass them to the base constructor in the constructor of the derived class.

class Creature
{
  public:
    Creature(int a, int s) : armor(a), strength(s) {};

protected:
    int armor;
    int strength;
};

class Human: public Creature
{
   public:
      Human(int a, int s) : Creature(a, s) {}
};

Note: you can make Creature constructor protected if you want only the derived classes to construct a Creature.

If you want to access armor and str values you will have to add getter functions, since armor and strength are protected member variables.

class Creature
{
  public:
    Creature(int a, int s) : m_armor(a), m_strength(s) {};

    int armor() const     { return m_armor; }
    int strength() const  { return m_strength; }

protected:
    int m_armor;
    int m_strength;
};

Now you can have your main() function:

int main() 
{ 
  Human Male(30, 50);
  cout << Male.armor();
  cout << Male.strength();
  return 0;
}
like image 179
rozina Avatar answered Aug 27 '26 11:08

rozina


Allow setting them these variables in a constructor in the base class:

class Creature
{
  public:
    Creature();
  protected:
    Creature(int armor_, int strength_) : armor(armor_), strength(strength_){}        

    int armor;
    int strength;
};

Now in the derived class, just pass these to the base class:

Human(int armor_, int strength_) : Creature(armor_, strength_){}     
like image 26
Ami Tavory Avatar answered Aug 27 '26 10:08

Ami Tavory



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!