Creating a default constructor on a subclass

18,374

Solution 1

You can create a parameterless constructor on the derived class, but it still needs to pass arguments to the base class constructor:

    //Default constructor
    public SoccerPlayer()
        : base("default name", 0, default(Sexs))
    {

    }

Or you could add a default constructor to the base class...

Solution 2

you can have a parameter less constructor in child class but you need to invoke the parameterized constructor of base or same class like so

public Child():base(1,2,3)
{
}

or

public Child(): this(1,2,3)
{
}

In your case it wouldn't make much sense though. A soccer player can't have a default name or age.

Solution 3

You can create your new constructor, but if you don't call base(...) something on base class couldn't be initialized.
So you should use:

public SoccerPlayer()
    :base("name", 30, Sexs.???)
{
}
Share:
18,374
OVERTONE
Author by

OVERTONE

3000 people view, 500 people favourite, 5 closed it all down.

Updated on July 28, 2022

Comments

  • OVERTONE
    OVERTONE almost 2 years

    I'm still learning C# and just had a basic question about inheritance.

    Lets say I have an abstract class SportsPlayer:

    public abstract class SportsPlayer
    {
    
        string name;    /*1ai*/
        int age;        /*1aii*/
        Sexs gender;    /*1aiii*/ 
    
        //1b
        public SportsPlayer(string n, int a, Sexs g)
        {
            this.name = n;
            this.age = a;
            this.gender = g;
        }
    }
    

    And a subclass called SoccerPlayer:

    public class SoccerPlayer : SportsPlayer
        {
            Positions position;
            public SoccerPlayer(string n, int a, Sexs g, Positions p)
                : base(n, a, g)
            {
                this.position = p;
            }
    
            //Default constructor
            public SoccerPlayer()
            {
    
            }
    

    Is it possible to create a constructor on the subclass which is passed no arguments or am I right in thinking that in order to create a default constructor on a subclass, the super class must have a default constructor too?


    Also, if I were to add a default constructor to the super class, how would I initialize the super class variables in the subclass constructor? In java its super(), in C# it's??

    public SoccerPlayer():base()
    {
        base.name = "";
    }
    

    ???