So I'm trying to teach myself to program and I'm making a rpg battle thing for practice. (basically just a very simple old rpg battle system in c#) However, I'm a little confused on inheritance. So I have a base class Enemy:
class Enemy
{
public string name;
public int health;
public int attack;
public int level;
public Enemy(string _name, int _health, int _attack, int _level)
{
name = _name;
health = _health;
attack = _attack;
level = _level;
}
}
And then I have this class Dragon
:
class Dragon : Enemy
{
}
Why is it saying that
there is no argument given that corresponds to the required formal parameter '_name' of 'Enemy.Enemy(string, int , int, int)?
My thought was that it would use the enemy constructor, Do I have to make each derived class its own constructor?
The basic answer to your question is yes. Your derived classes must define a constructor, specifically they must do so when no default constructor is available on the base class.
This is because base class constructors are always fired when derived classes are created (in fact, they are fired first). If you don't have a constructor to pass the base class constructor its required arguments, the compiler doesn't know how to handle this.
In your case, something like
public Dragon(string _name, int _health, int _attack, int _level)
:base(_name, _health, _attack, _level)
{
}
Will get you started. You may need (and can have) other parameters for your Dragon
of course. You can also pass literals into the base constructor (so you don't need to parameterize the Dragon
one with all base class arguments).
public Dragon(string _name)
:base(_name, 1000, 500, 10)
{
}
The only requirement is that an existing base class constructor is used.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With