OVERTONE
OVERTONE

Reputation: 12207

Creating a default constructor on a subclass

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 = "";
}

???

Upvotes: 6

Views: 21341

Answers (3)

Marco
Marco

Reputation: 57593

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.???)
{
}

Upvotes: 2

Thomas Levesque
Thomas Levesque

Reputation: 292755

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...

Upvotes: 7

Muhammad Hasan Khan
Muhammad Hasan Khan

Reputation: 35156

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.

Upvotes: 5

Related Questions