Home > database >  How to call constructor from derived class
How to call constructor from derived class

Time:03-04

Let say I have a Item base class

public class Item
{
    var SomeVariable;
    var OtherVariable;
    
    public Item(some parameter)
    {

    }
}

and a derived class called Gun

public class Gun : Item
{
    var SomeVariable;
    public Gun(Some Parameter)
    {

    }

}

and the Item class Constructor is represent as actual item in Inventory. like when player picked up GameObject with Item class attach to it it will added to the Inventory using the Method Add Item

public bool AddItem(Item _item, int _amount)
{
    //add Item to Inventory object
}

as you can see the Method Add Item is using Item as parameter, so when a Gun GameObject pickup by player it won't added to inventory do I need to change how the system work or it can be fixed ?

CodePudding user response:

Call the base constructor from your derived class in this way:

public class Gun : Item
{
    var SomeVariable;
    public Gun(Some Parameter) : base(Some Parameter)
    {
    }
}

But it's not clear what the actual issue is, since you don't need to initialize the passed Item in AddItem. Simply put it to your inventory instance. Assuming you have an instance of it there:

public bool AddItem(Item item, int amount)
{
    inventory.Add(item, amount); // just guessing
}

So when a Gun GameObject pickup by player it won't added to inventory do I need to change how the system work or it can be fixed ?

I think i get your misunderstanding now. Since a Gun actualls IS an Item, you can call AddItem with a Gun instance. That's one of the advantages of inheritance.

AddItem(new Gun(Some Parameter), 1);
  • Related