Search Unity

Derived class contructor not running base contructor

Discussion in 'Editor & General Support' started by JJMaelstrom, Jun 20, 2019.

  1. JJMaelstrom

    JJMaelstrom

    Joined:
    Jun 17, 2019
    Posts:
    2
    Code (CSharp):
    1. class Item
    2. {
    3.     public int id;
    4.  
    5.     public Item(int id)
    6.     {
    7.         this.id = id;
    8.     }
    9. }
    10.  
    11. class Weapon : Item
    12. {
    13.     public float damage;
    14.  
    15.     public Weapon(float damage)
    16.     {
    17.         this.damage = damage;
    18.     }
    19. }
    Error = "There is no argument given that corresponds to the required formal parameter 'id' of Item.Item(int)'

    Meanwhile on google, "Base class constructors are always called in the derived class constructors."

    I want to be able to do
    Weapon sword = new Weapon(0, 10.0f)
    but this whole thing has been needlessly complicated. Need help please.
     
  2. Vryken

    Vryken

    Joined:
    Jan 23, 2018
    Posts:
    2,106
    A same-argument constructor needs to exist in the parent and child classes in order for the child constructor to automatically call the parent constructor.

    Because the Weapon constructor requires a float argument, and the Item class does not have any constructors that take in a float argument, there is no parent constructor to call. This also means that the Weapon's inherited "id" field is never assigned as well.

    Since what you're trying to do here is instantiate a derived object with additional parameters to its parent object, you need to create an constructor that takes in arguments required for the parent fields as well as its own fields, then call the parent constructor manually with the supplied argument for the parent fields:

    Code (CSharp):
    1. class Item {
    2.    public int id;
    3.  
    4.    public Item(int id) {
    5.        this.id = id;
    6.    }
    7. }
    8.  
    9. class Weapon : Item {
    10.    public float damage;
    11.  
    12.    //The "base" keyword here is referencing the parent class.
    13.    //Passing in "id" here means we're calling a parent constructor that takes in a single integer argument.
    14.    public Weapon(int id, float damage) : base(id) {
    15.        this.damage = damage;
    16.    }
    17. }
     
    Joe-Censored likes this.