Can the constructor of a derived class have more parameters than the constructor of its base class?

  • A+
Category:Languages

I have a base class and 2 derived classes. The base class has a few simple protected float variables and the constructor for my base class is as follows:

public Enemy(float _maxhp, float _damage) {     maxhp = _maxhp;     health = _maxhp;     damage = _damage; } 

However, my derived class Range has 2 more float variables attack and attackSpeed that need to be passed in as arguments when creating a new instance of Range but I can't seem to be able to do that since an error saying There is no argument that corresponds to the required formal parameter '_maxhp' of 'Enemy.Enemy(float, float)' when I try to use a constructor for the derived class with these params:

public Range(float _maxhp, float _damage, float _attack, float _attackSpeed)

but a constructor with the same number of params works

public Range(float _maxhp, float _damage)

Why is this happening and is there some kind of workaround? Thanks in advance.

 


You have to specify how to call the constructor on the base class using the base() constructor call:

public Range(float _maxhp, float _damage, float _attack, float _attackSpeed)     : base(_maxhp, _damage) {     // handle _attack and _attackSpeed } 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: