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!
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.
Note: you can make
Creature
constructorprotected
if you want only the derived classes to construct aCreature
.If you want to access armor and str values you will have to add getter functions, since armor and strength are protected member variables.
Now you can have your main() function:
Allow setting them these variables in a constructor in the base class:
Now in the derived class, just pass these to the base class:
First, make sure that the base class has a constructor that can initialize its member variables properly.
Unless the derived class has other member data that need to be initialized, you can use the following construct to be able to use the base class constructor like it is also defined in the derived class.
Now you can use:
Use of
is not correct since
armor
andstrength
areprivate
member variables ofCreature
. You should add couple of accessor functions and use them.and then use them as: